我在从MongoDB检索特定半径内的正确日期时遇到一些问题。我在底部显示了一个json示例。我的目标是搜索接近定义的地理位置的所有项目以及过滤开始时间。这还包括创建正确的索引。目前没有很多指导和关于。提前感谢您的帮助。
总之,我要做的是:
此致 兰斯
如果我只想查询日期,我可以执行以下操作:
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"
}
]
}
答案 0 :(得分:3)
解决。为了让Jongo工作,我只需要使用正确的maxDistance。而不是EarthRadiusInMILES,我应该定义这个; Double ONE_DEGREE_IN_MILES = 69.11;
注意:1°纬度=约69.11英里