【问题标题】:Limit Multiple MongoDB Array Size限制多个 MongoDB 数组大小
【发布时间】:2012-07-24 17:17:44
【问题描述】:

我有一个文档,其中列出了按主题分隔的作者的帖子项目 ID。这会产生如下文档:

{
    _id: "sdkafjsadkfjads3023",
    Author: "SomeGuy"
    RecentPosts: {
        "topic-1": {
            Count: 4,
            Posts: ["postitemid1","postitemid2","postitemid2","postitemid3"]
        }
        "topic-2": {
            Count: 3
            Posts: ["postitem5","postitem6","postitem8"]
        }
    }
}

大多数时候,我在同一更新中对这些帖子数组中的每一个进行原子推送。我想要做的是始终将上面的数组限制为 10 个项目。这样,每当我对相同的主题/帖子进行推送时。我要问的是否可能,或者我应该以不同的方式做到这一点?

提前致谢

【问题讨论】:

  • 你能举例说明你是如何更新 Post[] 数组的吗?
  • 我决定简单地使用服务器端解决方案。我从个人资料中拉下最近的帖子,然后选择前 10 个并将其保存回个人资料。

标签: mongodb atomic fixed


【解决方案1】:

如果我理解正确 Capped Collections 就是您想要的。 http://www.mongodb.org/display/DOCS/Capped+Collections

【讨论】:

    【解决方案2】:

    事实证明,这是 MongoDB 中一个长期存在的问题,自从使用 $slice 运算符添加到 MongoDB 2.4 版本中之后。

    db.students.update(
                    { _id: 1 },
                    { $push: { scores: { $each : [
                                                   { attempt: 3, score: 7 },
                                                   { attempt: 4, score: 4 }
                                                 ],
                                         $sort: { score: 1 },
                                         $slice: -3
                                       }
                              }
                    }
                  )
    

    http://docs.mongodb.org/manual/tutorial/limit-number-of-elements-in-updated-array/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2018-03-26
      • 1970-01-01
      • 1970-01-01
      • 2012-05-13
      相关资源
      最近更新 更多