在MongoDB中,当有超过100条记录时,如何对2d索引$ near查询进行排序?

时间:2015-02-10 15:40:18

标签: mongodb mongoose geolocation mongodb-query

我有一个查询使用$near来过滤到附近的记录。然后应该通过单独的字段对结果进行排序。但是,即使符合条件,我也会遇到记录丢失的情况。

我怀疑这是因为使用带有$near索引的2d有100个记录限制。我认为正在发生的是地理空间排序首先发生,然后我的应用程序才被应用到该结果的前100个记录中。

无论如何都要克服这种行为?我可以忽略$near那种并使用我自己的主要排序,或者绕过100记录限制,以便我的排序适用于整个集合吗?

以下是我使用的查询中的explain()

db.properties.find({
  loc: { 
    $near: [-80.173366, 34.07868], 
    $maxDistance: 5 
 }}).sort({mls: -1}).explain()

{
    "cursor" : "GeoSearchCursor",
    "isMultiKey" : false,
    "n" : 100,
    "nscannedObjects" : 211,
    "nscanned" : 700,
    "nscannedObjectsAllPlans" : 211,
    "nscannedAllPlans" : 700,
    "scanAndOrder" : true,
    "indexOnly" : false,
    "nYields" : 1,
    "nChunkSkips" : 0,
    "millis" : 2,
    "indexBounds" : {

    },
    "server" : "slate:27017",
    "filterSet" : false
}

1 个答案:

答案 0 :(得分:1)

前一段时间我遇到了同样的问题,你可以使用aggregate - $ match。我在hackaton上使用了以下代码段。

db.kickstarter.aggregate(   
                            {'$match' : 
                                {geo2 :
                                    {$geoWithin :
                                        { $centerSphere :[[parseFloat(lng), parseFloat(lat) ], radius/6371 ] 
                                        }
                                    }
                                }
                            },
                            {$sort : {'pledged' : -1}},
                            {$limit : 1000}, //you can set your limit here
                            function(err, data){
                                if(err)console.log(err);
                            }
                        );