MongodDB $拉离数组只有一个元素 [英] MongodDB $pull only one element from array

查看:201
本文介绍了MongodDB $拉离数组只有一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组一个文档中,就像这样:

I have a document with an array inside, like this:

"userTags" : [
        "foo",
        "foo",
        "foo",
        "foo",
        "moo",
        "bar"
    ]

如果我执行 db.products.update({criteriaToGetDocument},{$推:{userTags:富}}} 我能正确地插入的另一个实例入阵。

If I perform db.products.update({criteriaToGetDocument}, {$push: {userTags: "foo"}}} I can correctly insert another instance of foo into the array.

但是,如果我这样做 db.products.update({criteriaToGetDocument},{$拉:{userTags:富}}} 然后删除的所有的从阵列的实例,让我:

However, if I do db.products.update({criteriaToGetDocument}, {$pull: {userTags: "foo"}}} then it removes all instances of foo from the array, leaving me with:

"userTags" : [
        "moo",
        "bar"
    ]

这将根本不行,我只是想从阵列,而不是所有的人拉一个项目。我怎么能这样,只有一个被删除修改命令?是否有某种 $ pullOnce 方法,可以在这里工作?

This won't do at all, I only want to pull one item from the array rather than all of them. How can I alter the command so that only one foo is removed? Is there some sort of $pullOnce method that can work here?

推荐答案

没有,有没有这样的时刻。很多人已经请求的功能,你可以跟踪它在 MongoDB的吉拉。至于你所看到的问题没有解决,也没有预定(这意味着你必须在不久的将来没有运气)。

No, there is nothing like this at the moment. A lot of people already requested the feature and you can track it in mongodb Jira. As far as you can see it is not resolved and also not scheduled (which means you have no luck in the near future).

的唯一选择是使用应用程序逻辑来实现,这将是:

The only option is to use application logic to achieve this would be:


  1. 找到您想要的元素并具有userTags作为富

  2. 通过userTags迭代,并从中删除一个富

  3. 更新元素与新的userTags

请记住,此操作中断原子性,但由于蒙戈并没有提供一个本地方法的话,你会以任何方式打破原子。

Keep in mind that this operation breaks atomicity, but because Mongo has not provided a native method to do so, you will break atomicity in any way.

我移动一个替代解决方案的新的答案,因为它没有回答这个问题,但再presents的方法之一来重构现有的模式。这也成了大不大,说开始大得多那么原来的答案。

I moved one alternative solution to the new answer, because it does not answer this question, but represents one of the approaches to refactor existing schema. It also became so big, that started to be much bigger then the original answer.

这篇关于MongodDB $拉离数组只有一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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