我熟悉大型MongoDB集合中基于范围的分页的最佳实践,但是我正在努力弄清楚如何对排序值在非唯一字段上的集合进行分页.
例如,我有大量的用户,并且有一个字段表示他们做过某些事情的次数.此字段绝对不是唯一的,并且可能具有大量具有相同值的文档.
我想返回按'numTimesDoneSomething'字段排序的结果.
这是一个示例数据集:
{_id: ObjectId("50c480d81ff137e805000003"), numTimesDoneSomething: 12}
{_id: ObjectId("50c480d81ff137e805000005"), numTimesDoneSomething: 9}
{_id: ObjectId("50c480d81ff137e805000006"), numTimesDoneSomething: 7}
{_id: ObjectId("50c480d81ff137e805000007"), numTimesDoneSomething: 1}
{_id: ObjectId("50c480d81ff137e805000002"), numTimesDoneSomething: 15}
{_id: ObjectId("50c480d81ff137e805000008"), numTimesDoneSomething: 1}
{_id: ObjectId("50c480d81ff137e805000009"), numTimesDoneSomething: 1}
{_id: ObjectId("50c480d81ff137e805000004"), numTimesDoneSomething: 12}
{_id: ObjectId("50c480d81ff137e805000010"), numTimesDoneSomething: 1}
{_id: ObjectId("50c480d81ff137e805000011"), numTimesDoneSomething: 1}
Run Code Online (Sandbox Code Playgroud)
如何返回按'numTimesDoneSomething'排序的数据集,每页有2条记录?
@cubbuk使用offset(skip)显示了一个很好的例子,但你也可以模拟他为远程分页显示的查询:
db.collection.find().sort({numTimesDoneSomething:-1, _id:1})
Run Code Online (Sandbox Code Playgroud)
因为_id这里将是独一无二的,你是借调它实际上你可以再利用的范围_id和效果,即使两个记录之间具有numTimesDoneSomething的12,应该是他们是否应该是一个页面或下一上是一致的.
所以做一些简单的事情
var q = db.collection.find({_id: {$gt: last_id}}).sort({numTimesDoneSomething:-1, _id:1}).limit(2)
Run Code Online (Sandbox Code Playgroud)
应该对远程分页工作相当好.
| 归档时间: |
|
| 查看次数: |
1762 次 |
| 最近记录: |