具有Distinct和Sorted值的MongoDB geoNear

时间:2014-03-29 05:47:43

标签: php mongodb aggregation-framework geospatial

我的收藏集包含以下字段,存储用户签到(地理坐标)

{
    "_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 }
        } 
    } 
)

告诉我哪里错了!

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值。

认为是你想要的。