我在从 MongoDB 检索特定半径内的正确日期时遇到了一些问题。我在底部显示了一个 json 示例。我的目标是搜索靠近定义地理位置的所有项目,并在开始时间进行过滤。这还包括创建正确的索引。目前没有太多的指导。提前感谢您的帮助。
总之,我想做的是:
- 从 MongoDB 检索位于提供的地理位置 3 英里范围内的所有项目
- 筛选开始时间在 x 之后但在 y 之前的项目的结果。
- 创建一个适用于我的查询的索引。
问候, 兰斯
如果我只想查询日期,我可以执行以下操作:
DateTime maxdateTime = new DateTime(); //Joda Time
//Adjust my datetime, simply add 2 hours to the time
DateTime mindateTime = new DateTime(); Joda Time
//Adjust my datetime, subtract 1 day
Date maxDate = new Date(maxdateTime.getMillis());
Date minDate = new Date(mindateTime.getMillis());
DBCollection coll = db.getCollection("BikeRides");
coll.ensureIndex( { startTime:1, } )
BasicDBObject query = new BasicDBObject();
query.put("startTime", BasicDBObjectBuilder.start("$gte", minDate).add("$lte", maxDate).get());
DBCursor cursor = coll.find(query);
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
如果我只想查询 GeoLocation,我可以执行以下操作:
//A GeoLoc is passed into this method
int distance = 3;
int earthRadius = 3963.192;
DBCollection coll = db.getCollection("BikeRides");
coll.ensureIndex( { Location.GeoLoc : "2d" } )
db.runCommand( { geoNear: "BikeRides",
nearSphere: [ "Location.GeoLoc.latitude": geoLoc.longitude, "Location.GeoLoc.longitude": geoLoc.latitude ]
maxDistance: distance / earthRadius
} )
我也和 Jongo 一起尝试过,但没有成功:
DateTime nowDateTime = new DateTime(DateTimeZone.UTC); // Joda time
DateTime maxStartTime = nowDateTime.plusMinutes(TIME_IN_MINUTES);
DateTime minStartTime = nowDateTime.minusDays(1); //This will cut out most old bike rides
Long now = nowDateTime.toInstant().getMillis();
Long max = maxStartTime.toInstant().getMillis();
Long min = minStartTime.toInstant().getMillis();
//Get the objects using Jongo
MongoCollection bikeRidesCollection = MongoDatabase.Get_DB_Collection(MONGO_COLLECTIONS.BIKERIDES, "Location.GeoLoc");
//Currently not placing a limit on this result. If we find this is an issue we can add later.
bikeRidesCollection.ensureIndex("{Location.GeoLoc: '2d', RideStartTime: 1}");
Iterable<BikeRide> all = bikeRidesCollection
.find("{Location.GeoLoc: {$near: [#, #], $maxDistance: #}, RideStartTime: {$lte: #, $gte: #}}", //, $maxDistance: #
location.getGeoLoc().longitude,
location.getGeoLoc().latitude,
RADIUS_IN_MILES/EarthRadiusInMILES,
max ,
min )
.as(BikeRide.class);
List<BikeRide> closeBikeRides = Lists.newArrayList(all);
我的示例 Json:
{
"BikeRides": [
{
"StartTime": "2013-03-08T00:01:00.000 UTC",
"bikeRideName": "Strawberry Ride",
"id": "513afc2d0364b81b8abfa86e",
"location": {
"city": "Portland",
"geoLoc": {
"longitude": "-122.71446990966797",
"latitude": "45.49216842651367"
},
"state": "OR",
"streetAddress": "4214 SE 36th"
},
"startTime": "2013-03-07T16:01:00-08:00"
}
]
}