【问题标题】:Iterating over documents with equals values迭代具有相等值的文档
【发布时间】:2012-11-09 18:11:01
【问题描述】:

我在 mongo db 中有一组带有“votes”字段的博客文章:

> db.posts.find({}, {_id:0, votes: 1})
{ "votes" : 1 }
{ "votes" : 2 }
{ "votes" : 2 }
{ "votes" : 3 }
{ "votes" : 3 }

比我有一个网络界面来显示每页一个帖子和控件(下一个,上一个)来滑动按投票排序的帖子。我将下一个/上一个帖子的请求发送到具有当前投票计数的服务器并选择新的。所以我得到下一个查询(每个 http 请求一个)

> db.things.find({vote: {$gt: 0}}, {_id:0, votes:1}).limit(1) // current votes == 0
{ "votes" : 1 }
> db.things.find({vote: {$gt: 1}}, {_id:0, votes:1}).limit(1) // current votes == 1
{ "votes" : 2 }
> db.things.find({vote: {$gt: 2}}, {_id:0, votes:1}).limit(1) // current votes == 2
{ "votes" : 3 }
...

如您所见,跳过了等于“投票”的文档。所以我需要一些方法来使文档唯一并迭代相等的投票(投票字段可能会经常更新,并且每个文档都有许多相等的值)。

有什么办法可以解决这个问题吗?看起来我需要某种搜索索引。但正如我所说,标准字段变化非常频繁,我计划拥有数百万个文档。这意味着索引更新将是非常昂贵的操作,我希望系统对更新做出安全响应。

【问题讨论】:

    标签: mongodb mongodb-query database nosql


    【解决方案1】:

    如果您不关心返回结果的顺序,您应该按_id 对它们进行排序,然后使用{$gt: current_id} 得到下一个:

    db.things.findOne({}, {votes: 1}).sort({_id: 1}) // _id == 0
    db.things.findOne({_id: {$gt: 0}}, {votes: 1}).sort({_id: 1}) // _id == 1
    db.things.findOne({_id: {$gt: 1}}, {votes: 1}).sort({_id: 1}) // _id == 2
    ...
    

    如果您需要通过votes 订购它们,那么您需要使用skip 代替:

    db.things.findOne({}, {votes: 1}).sort({votes: 1})
    db.things.findOne({}, {votes: 1}).sort({votes: 1}).skip(1)
    db.things.findOne({}, {votes: 1}).sort({votes: 1}).skip(2)
    ...
    

    但随着您必须越跳越远进入结果集,这会变得越来越慢。

    【讨论】:

      猜你喜欢
      • 2020-01-08
      • 1970-01-01
      • 2018-06-08
      • 1970-01-01
      • 2019-11-07
      • 1970-01-01
      • 2019-11-13
      • 2021-05-24
      • 1970-01-01
      相关资源
      最近更新 更多