Reputation: 7666
I am trying to update multiple embedded documents in multiple documents in MongoDB using mongoose in nodejs.
An example of the document is shown below.
As you can see, in a 'exampleDocument' there is an embedded document: 'embededDoc'.
let exampleDocument =
{
_id: '1aa',
player_id: '9pp',
docUpdated: false',
embededDoc:
[
{
_id: '3eb',
embededDocUpdated: false,
timeDocWasSaved: '2019-04-30T08:45:50.349Z'
}
],
}
How can I update multiple embedded 'embededDoc' documents in multiple 'exampleDocument' documents.
With the help of this answer I know how to update multiple documents with a single command like you can see below:
db.exampleDocument.update(
{ _id: { $in: ['1aa', '2bb', '3cc'] } },
{ $set: { docUpdated : yes } }
)
What if I wanted to update several embeded documents(embededDoc) by their ids?
For example assuming we have three 'exampleDocument' documents with the ids: '1aa', '2bb', '3cc'. And each of these documents has five embeded documents and I wanted to update some of the embeded documents by their ids... is it possible to do it with one command or will I have to do it document by document?
If possible I would really appreciate a code example with the answer, thank you.
Upvotes: 1
Views: 441
Reputation: 1896
You have to use filtered positional update operater $[elem]
, Try below solution, i have tested it with some sample documents given below:
Solution:
db.test.update({
_id: {
$in: ['1aa', '1bb', '1cc']
}
}, {
$set: {
"embededDoc.$[elem].embededDocUpdated": true,
"docUpdated" : "yes"
}
}, { arrayFilters: [{"elem._id": {$in: ['3ed',"3eg","3eb","3eh"]}}], multi: true})
i have tested above query with below sample Documents and its working fine as you want:
[{
"_id" : "1cc",
"player_id" : "9pp",
"docUpdated" : false,
"embededDoc" : [
{
"_id" : "3ed",
"embededDocUpdated" : false,
"timeDocWasSaved" : "2019-04-30T08:45:50.349Z"
},
{
"_id" : "3eh",
"embededDocUpdated" : false,
"timeDocWasSaved" : "2019-04-30T08:45:50.349Z"
}
]
},
{
"_id" : "1bb",
"player_id" : "9pp",
"docUpdated" : false,
"embededDoc" : [
{
"_id" : "3ec",
"embededDocUpdated" : false,
"timeDocWasSaved" : "2019-04-30T08:45:50.349Z"
},
{
"_id" : "3eg",
"embededDocUpdated" : false,
"timeDocWasSaved" : "2019-04-30T08:45:50.349Z",
}
]
},
{
"_id" : "1aa",
"player_id" : "9pp",
"docUpdated" : false,
"embededDoc" : [
{
"_id" : "3eb",
"embededDocUpdated" : false,
"timeDocWasSaved" : "2019-04-30T08:45:50.349Z",
},
{
"_id" : "3ef",
"embededDocUpdated" : false,
"timeDocWasSaved" : "2019-04-30T08:45:50.349Z"
}
]
}]
Upvotes: 1
Reputation: 1124
Try with this
db.collection.update(
{ "embededDoc._id": "3eb" },
{ $set: { "embededDoc.$.embededDocUpdated" :true } }
)
Upvotes: 1