我只记录我用到的部分,没有完整分析mongodb对地理位置的支持
1. 使用mongodb 3.2.6版,mongodb-driver 3.2.2版
2. 使用GeoSpatial索引:
use dbName db.collectionName.ensureIndex({"location": "2dsphere"})
3. 查询一定距离范围内的记录:
// 查询fieldA不等于not_equal_value,status等于1,距离范围为100-2000米之内的第11-20行记录 double longitude = 120.21533; double latitude = 30.253708; int start = 10; int limit = 20; Bson query = Filters.and(Filters.ne("fieldA", "not_equal_value"), Filters.eq("status", 1), Filters.nearSphere("location", new Point(new Position(longitude, latitude)), 2000d, 100d)); MongoCollection<Document> collection = getCollection("dbName", "collectionName"); FindIterable<Document> findIter = collection.find(query); findIter = findIter.skip(start); findIter = findIter.limit(size); MongoCursor<Document> cursor = findIter.iterator(); Document document = null; while (cursor.hasNext()) { document = cursor.next(); // do with document }
4. 查询距离最近的n条记录
// 查询status等于1,距离最近的10条记录 db.runCommand({geoNear:"collectionName", near:[120.21533, 30.253708], distanceMultiplier:6378137, num:10, spherical:true, query:{"status":1}})