限制多个MongoDB阵列大小 [英] Limit Multiple MongoDB Array Size

查看:71
本文介绍了限制多个MongoDB阵列大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文档,其中列出了按主题分开的作者的文章ID.这样会得到如下文档:

I have a document that lists post item ids for an author separated out by topic. This results in a document such as the following:

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

大多数时候,我在同一更新中对每个发布数组进行原子推送.我想做的是始终将上述数组限制为10个项目.这样,任何时候我都对相同的主题/帖子进行全力以赴.我要问的甚至有可能吗?还是应该以其他方式这样做?

Most of the time I am doing atomic pushes to each of these post arrays in the same update. What I want to do is limit the arrays above to 10 items at all times. This way, anytime I do a pushall to the same topic/posts. Is what I'm asking even possible, or should I do this a different way?

预先感谢

推荐答案

事实证明,这是MongoDB中的一个长期存在的问题,此问题是在MongoDB 2.4版本中使用$ slice运算符添加的.

As it turns out, this was a longstanding issue in MongoDB that was since added in MongoDB 2.4 release using the $slice operator.

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/

这篇关于限制多个MongoDB阵列大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆