Geonear 按距离和时间排序

Geonear sort by distance and time

我有以下数据:

{ 
    "_id" : ObjectId("55a8c1ba3996c909184d7a22"),
    "uid" : "1db82e8a-2038-4818-b805-76a46ba62639",
    "createdate" : ISODate("2015-07-17T08:50:02.892Z"),
    "palce" : "aa",
    "sex" : 1,
    "longdis" : 1,
    "location" : [ 106.607312, 29.575281 ]
}
{ 
    "_id" : ObjectId("55a8c1ba3996c909184d7a24"),
    "uid" : "1db82e8a-2038-4818-b805-76a46ba62639",
    "createdate" : ISODate("2015-07-17T08:50:02.920Z"),
    "palce" : "bbb",
    "sex" : 1,
    "longdis" : 1,
    "location" : [ 106.589896, 29.545098 ]
}
{
    "_id" : ObjectId("55a8c1ba3996c909184d7a25"),
    "uid" : "1db82e8a-2038-4818-b805-76a46ba62639",
    "createdate" : ISODate("2015-07-17T08:50:02.922Z"),
    "palce" : "ccc",
    "sex" : 1,
    "longdis" : 1,
    "location" : [ 106.590758, 29.566713 ]
}
{
    "_id" : ObjectId("55a8c1ba3996c909184d7a26"),
    "uid" : "1db82e8a-2038-4818-b805-76a46ba62639",
    "createdate" : ISODate("2015-07-17T08:50:02.923Z"),
    "palce" : "ddd",
    "sex" : 1, 
    "longdis" : 1, 
    "location" : [ 106.637039, 29.561436 ]
}
{
    "_id" : ObjectId("55a8c1bc3996c909184d7a27"),
    "uid" : "1db82e8a-2038-4818-b805-76a46ba62639",
    "createdate" : ISODate("2015-07-17T08:50:04.499Z"),
    "palce" : "eee",
    "sex" : 1,
    "longdis" : 1,
    "location" : [ 106.539522, 29.57929 ]
}
{ 
    "_id" : ObjectId("55a8d12e78292fa3837ebae4"),
    "uid" : "1db82e8a-2038-4818-b805-76a46ba62639",
    "createdate" : ISODate("2015-07-17T09:55:58.947Z"),
    "palce" : "fff",
    "sex" : 1,
    "longdis" : 1,
    "location" : [ 106.637039, 29.561436 ]
}

我想先按距离排序,如果距离相同,按时间排序。

我的命令:

db.runCommand( { 
   geoNear: "paging", 
   near: [106.606033,29.575897 ],
   spherical : true,
   maxDistance : 1/6371,
   minDistance:0/6371,
   distanceMultiplier: 6371,
   num:2,
   query: {'_id': {'$nin': []}} 
})

db.paging.find({
   'location':{
       $nearSphere: [106.606033,29.575897],
       $maxDistance:1
   }
}).limit(5).skip((2 - 1) * 2).sort({createdate:-1})

如何对 "nearest" 和 "createddate" 进行排序?

此处使用的正确查询使用 aggregation framework which has the $geoNear 管道阶段来协助完成此操作。这也是您通过多个键到达 "sort" 的唯一地方,不幸的是 "geospatial" $nearSphere 没有像 [=13] 这样的 "distance" 的 "meta" 投影=] 有一个 "score".

此外,您正在使用的 geoNear 数据库命令也不能以这种方式与 "cursor" .sort() 一起使用。

db.paging.aggregate([
    { "$geoNear": {
        "near": [106.606033,29.575897 ],
        "spherical": true,
        "distanceField": "distance",
        "distanceMuliplier": 6371,
        "maxDistance": 1/6371
    }},
    { "$sort": { "distance": 1, "createdate": -1 } },
    { "$skip": ( 2-1 ) * 2 },
    { "$limit": 5 }
])

这相当于您正在尝试做的事情。

借助聚合框架,您可以使用 "pipeline operators" 而不是 "cursor modifiers" 来执行 $sort$skip$limit 等操作。此外,这些 必须 符合逻辑顺序,而游标修饰符通常会解决它。

这是一个 "pipeline",就像 "Unix pipe" 一样。 |

此外,请注意 "maxDistance" 和 "distanceMuliplier"。由于您的坐标采用 "legacy co-ordinate pairs" 而不是 GeoJSON 格式,因此距离以 "radians" 测量。如果您有 GeoJSON 存储的位置数据,那么结果将在 "meters".

中返回