Issue: updating value inside the subdocument of a subdocument

空扰寡人 提交于 2019-12-23 22:08:05

问题


I am having some trouble trying to update some fields of a subdocument inside a subdocument in mongodb.

First of all, let's find exactly the document I need to update to see how the document structure looks like:

// query:
db.getCollection('collection').find({
    application: ObjectId("568b3a2feaa4171d03734776"),
    _id: ObjectId("568b3a2feaa4171d03734779"),
    status: 'sent',
    'mailingList.recipients.email': 'example@example.com' // an index
},
{
    'mailingList.$.recipients': true
});

// query result:
{
    "_id" : ObjectId("568b3a2feaa4171d03734779"),
    "mailingList" : [ 
        {
            "id" : 55,
            "recipients" : [ 
                {
                    "metadata" : {
                        "name" : "Example",
                        "surname" : "Example"
                    },
                    "email" : "example@example.com",
                    "message" : {
                        "events" : []
                    }
                }
            ]
        }
    ]
}

What I would like to achieve is exactly being able to update any of the fields in the object inside recipients[]: let's say, for example, email. I've tried the following so far, using the $set operator:

db.getCollection('collection').update({
    application: ObjectId("568b3a2feaa4171d03734776"),
    _id: ObjectId("568b3a2feaa4171d03734779"),
    status: 'sent',
    'mailingList.recipients.email': 'example@example.com'
},
{
    $set: {
        'mailingList.$.recipients.email': 'newmail@example.com'
    }
});

but I get the following error:

cannot use the part (recipients of mailingList.1.recipients.email) to traverse the element ({recipients: [ { metadata: { name: "Example", surname: "Example" }, email: "example@example.com", message: { events: [] } } ]})

What am I missing? I had already worked with embedded subdocuments before (not like this where there is a subdocument inside another subdocument) and using $set was enough to update any field inside a single subdocument, i.e:

$set: {
    'mailingList.$.email': 'newmail@gmail.com'
}

来源:https://stackoverflow.com/questions/34604069/issue-updating-value-inside-the-subdocument-of-a-subdocument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!