我的收藏集包含以下字段,存储用户签到(地理坐标)
{
"_id" : ObjectId("5333c3063b15ea390b3c986a"),
"userID" : "5332cad33b15eaaf643c986a",
"timestamp" : ISODate("2014-03-27T06:19:50.129Z"),
"loc" : {
"type" : "Point",
"coordinates" : [
76.980286,
10.934041
]
}
}
{
"_id" : ObjectId("53353a0d3b15ea063a3c986a"),
"userID" : "533268983b15ea9f5a3c986c",
"timestamp" : ISODate("2014-03-28T08:59:57.907Z"),
"loc" : {
"type" : "Point",
"coordinates" : [
76.980019,
10.934072
]
}
}
{
"_id" : ObjectId("53353a5d3b15eacc393c986c"),
"userID" : "533268983b15ea9f5a3c986c",
"timestamp" : ISODate("2014-03-28T09:01:17.479Z"),
"loc" : {
"type" : "Point",
"coordinates" : [
76.980057,
10.933996
]
}
}
我正在使用geoNear来计算距离。 结果应该是最新的用户签到(地理坐标),即根据时间戳进行排序,以获得最新的签入,并根据 userID
进行分类我正在尝试以下代码,但它没有帮助
db.runCommand(
{
"geoNear" : "locations",
"near" : [76.980286, 10.934041 ],
"num" : 100,
"spherical" : true,
"maxDistance" :1000,
"query" : {
"distinct" : { "userID" : true } ,
"sort" : { "timestamp" : -1 }
}
}
)
告诉我哪里错了!
答案 0 :(得分:1)
再次看一下,似乎想要的是.aggregate()
表单,自2.4发行版以来一直可用:
db.users.aggregate([
{ "$geoNear": {
"near" : [76.980286, 10.934041 ],
"num" : 100,
"spherical" : true,
"maxDistance" :1000,
"distanceField": "calculated"
}},
{ "$sort": { "timestamp": -1, "calculated": 1 } },
{ "$group": {
"_id": "$userID",
"loc": { "$first": "$loc" },
"calculated": { "$first": "$calculated" }
}},
])
所以这样做是在聚合中使用$geoNear
运算符,以便" project" a" distanceField"这里基于" geo index"。然后你实际上似乎想要$sort
这些结果,但逻辑要做的事情是" sort"通过" timestamp"获得最新值,然后计算距离"作为"最近的"。
您的操作的最后一部分是您想要" distinct" userID
值。因此,您可以在此处使用$group
来获取结果,在之后使用sort然后应该是在分组边界上找到的$first
项。
这样应该为您提供" distinct"最近的用户#34;基于"最新"到达给定位置timestamp
值。
我认为是你想要的。