I have mongo document like that:
{
"_id" : ObjectId("61b4cd63465cd7ace1e12341"),
"artist" : "Short",
"album" : "Track",
"tracks" : [
{
"title" : "100m",
"length" : 10
},
{
"title" : "200m",
"length" : 20,
"guest" : "Big Bad"
}
]
}
I'm trying to add field quest to the tracks array with title 100m.
So that a document looks like that:
{
"_id" : ObjectId("61b4cd63465cd7ace1e12341"),
"artist" : "Short",
"album" : "Track",
"tracks" : [
{
"title" : "100m",
"length" : 10,
"guest": : "John Travolta"
},
{
"title" : "200m",
"length" : 20,
"guest" : "Big Bad"
}
]
}
I was tryin got achive that using db.collection.update and $set, but no good results.
How can I achieve that?
CodePudding user response:
You have to use positional operator $ like this:
db.collection.update({
"tracks.title": "100m"
},
{
"$set": {
"tracks.$.guest": "John Travolta"
}
})
This query tells to mongo "For the element into the tracks array where the title is 100m, insert the field guest with value John Travolta". And all of this using $ and the query stage "tracks.title": "100m"
Example here
