如何浏览MongoDB集合,其中排序基于整数属性?

时间:2015-07-02 18:10:23

标签: mongodb

给出如下文件:

{"points": 5},
{"points": 3},
{"points": 5},
{"points": 1}

我想一次查询(例如)2个文档,然后查询接下来的2个文档,按points对整个文档进行排序。所以,结果将是:

查询1:{"points": 5}, {"points": 5}

查询2:{"points": 3}, {"points": 1}

我尝试在points上创建索引以及在points_id上创建复合索引,以尝试查询包含索引的所有文档"大于"最后一个_id,或两个值的串联等。我尝试的任何东西都没有用。这似乎微不足道,我敢打赌,我错过了一些有助于我实现这一目标的索引。

1 个答案:

答案 0 :(得分:3)

您可以这样查询数据

For Each variable_name In collection_name
   'Some code here.
Next variable_name

编辑:

 > db.example.find().skip(0).limit(2).sort({"points":-1})
     { "_id" : ObjectId("559583bcb3a5b29213f845eb"), "points" : 5 }
     { "_id" : ObjectId("559583d1b3a5b29213f845ed"), "points" : 5 }
 > db.example.find().skip(2).limit(2).sort({"points":-1})
     { "_id" : ObjectId("559583cab3a5b29213f845ec"), "points" : 3 }
     { "_id" : ObjectId("559583d5b3a5b29213f845ee"), "points" : 1 }

编辑2:

也许这个解决方案可行。在此解决方案中,您将使用范围来搜索低于上次检索点的点。但是,问题是如果您有更多值为6的点未显示。在这种情况下,它会被跳过,因此您可以将此方法与某些应用程序逻辑结合起来解决问题:

> db.example.find().sort({"points":-1});
  { "_id" : ObjectId("5595923e66c8f5eb6958fd0c"), "points" : 12 }
  { "_id" : ObjectId("5595923966c8f5eb6958fd0b"), "points" : 11 }
  { "_id" : ObjectId("5595920066c8f5eb6958fd0a"), "points" : 10 }
  { "_id" : ObjectId("559591f766c8f5eb6958fd09"), "points" : 9 }
  { "_id" : ObjectId("559591a566c8f5eb6958fd08"), "points" : 8 }
  { "_id" : ObjectId("5595918f66c8f5eb6958fd07"), "points" : 7 }
  { "_id" : ObjectId("5595916d66c8f5eb6958fd06"), "points" : 6 }
  { "_id" : ObjectId("559583bcb3a5b29213f845eb"), "points" : 5 }
  { "_id" : ObjectId("559583d1b3a5b29213f845ed"), "points" : 5 }
  { "_id" : ObjectId("559583cab3a5b29213f845ec"), "points" : 3 }
  { "_id" : ObjectId("559583d5b3a5b29213f845ee"), "points" : 1 }
> db.example.find().skip(2).limit(2).sort({"points":-1});
  { "_id" : ObjectId("5595920066c8f5eb6958fd0a"), "points" : 10 }
  { "_id" : ObjectId("559591f766c8f5eb6958fd09"), "points" : 9 }
> db.example.insert({"points":14});
  WriteResult({ "nInserted" : 1 })
> db.example.insert({"points":15});
  WriteResult({ "nInserted" : 1 })
> db.example.find().skip(4).limit(2).sort({"points":-1});
  { "_id" : ObjectId("5595920066c8f5eb6958fd0a"), "points" : 10 }
  { "_id" : ObjectId("559591f766c8f5eb6958fd09"), "points" : 9 }

希望这会有所帮助。 卓然