1
我有一些問題從MongoDB中檢索特定半徑內的正確日期。我在底部顯示了一個json示例。我的目標是搜索接近定義的地理位置的所有項目以及在啓動時間進行篩選。這還包括創建正確的索引。目前沒有太多的指導。預先感謝您的幫助。具有地理位置和在指定時間範圍內的Java/Mongo查詢
綜上所述,我想要做的是:
- 檢索MongoDB中有3英里提供的地理位置的
- 篩選結果中,對於X之後,但在與開始時間的項目所有項目年。
- 創建適用於我的查詢的索引。
問候, 蘭斯
如果我只是想查詢的日期,我可以做到以下幾點:
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"
}
]
}
已解決。我只需要使用正確的maxDistance; Double ONE_DEGREE_IN_MILES = 69.11; //緯度1°=大約69.11英里 – LanceP 2013-03-12 08:45:10