如何从数组中提取子文档? [英] How can I pull sub-documents from an array?

查看:70
本文介绍了如何从数组中提取子文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个文件

{
    "_id" : ObjectId("56877d72572434211f8c579e"),
    "hola" : {
            "nombres" : [
                    "andres",
                    "jose"
            ]
    },
    "id" : "8888",
    "aloh" : [
            {
                    "saludo" : [
                            {
                                    "qwe" : "rty",
                                    "sad" : "fet"
                            },
                            {
                                    "dvo" : "rak",
                                    "foo" : "foo"
                            }
                    ]
            },
            {
                    "despedida" : "bye"
            }
    ]
}

我想删除包含的对象

{
    "qwe" : "rty",
    "sad" : "fet"
}

I我正在尝试使用$ pull和$ elemMatch这样:

I'm trying using $pull and $elemMatch like this:

db.collection.update(
    { "id":"8888" },
    { "$pull": { "aloh": { "saludo": { "$elemMatch": { "qwe": "rty" } } } } }
)

但它消除了所有父数组,我希望它输出如下内容:

But it eliminates all the parent array and I want it to output something like this:

{
    "_id" : ObjectId("56877d72572434211f8c579e"),
    "hola" : {
            "nombres" : [
                    "andres",
                    "jose"
            ]
    },
    "id" : "8888",
    "aloh" : [
            {
                    "saludo" : [
                            {
                                    "dvo" : "rak",
                                    "foo" : "foo"
                            }

                    ]
            },
            {
                    "despedida" : "bye"
            }
    ]
}


推荐答案

在这种情况下你使用位置 $ 更新运算符。需要注意的一点是,数组字段必须作为查询文档的一部分出现。这就解释了使用 $这里存在

It's in situation like this that you use the positional $ update operator. One thing to note is that the array field must appear as part of the query document. That is what explain the use of $exists here.

db.collection.update(
    { "id": "8888",  "aloh.saludo": { "$exists": true } }, 
    { "$pull": { "aloh.$.saludo": { "qwe": "rty", "sad": "fet" } } }
)

这篇关于如何从数组中提取子文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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