在MongoDB中,如何按位置过滤,按其他字段排序并正确分页结果?

时间:2012-02-09 18:08:29

标签: mongodb

当我不使用分页时,一切正常(我在这个集合中只有3条记录,因此所有这些都列在这里):

db.suppliers.find({location: {$near: [-23.5968323, -46.6782386]}},{name:1,badge:1}).sort({badge:-1})
{ "_id" : ObjectId("4f33ff549112b9b84f000070"), "badge" : 3, "name" : "Dedetizadora Alvorada" }
{ "_id" : ObjectId("4f33ff019112b9b84f00005b"), "badge" : 2, "name" : "Sampex Desentupidora e Dedetizadora" }
{ "_id" : ObjectId("4f33feae9112b9b84f000046"), "badge" : 1, "name" : "Higitec Desentupimento e Dedetização" }

但是当我尝试从第一页到第二页分页时,一条记录没有显示,一条记录重复:

db.suppliers.find({location: {$near: [-23.5968323, -46.6782386]}},{name:1,badge:1}).sort({badge:-1}).skip(0).limit(2)
{ "_id" : ObjectId("4f33ff549112b9b84f000070"), "badge" : 3, "name" : "Dedetizadora Alvorada" }
{ "_id" : ObjectId("4f33feae9112b9b84f000046"), "badge" : 1, "name" : "Higitec Desentupimento e Dedetização" }

db.suppliers.find({location: {$near: [-23.5968323, -46.6782386]}},{name:1,badge:1}).sort({badge:-1}).skip(2).limit(2)
{ "_id" : ObjectId("4f33feae9112b9b84f000046"), "badge" : 1, "name" : "Higitec Desentupimento e Dedetização" }

我做错了什么或是某种错误?


修改

Here is解决此问题的方法。基本上你不应该将$ near查询与排序混合在一起;改为使用$ within。

1 个答案:

答案 0 :(得分:3)

关于同样的问题存在一个未解决的问题。请看看&投票Geospatial result paging fails when sorting with additional keys