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'
}