I have 2 documents in a collection with a structure like below. I want to update "Source" as Home where environment is "QA" and Name is "Alan".
{
environment: DevA,
data: [
{
Name: "John",
Source: "Home"
},
{
Name: "Alan",
Source: "Office"
},
{
Name: "Susan",
Source: "Office"
}
],
},
{
environment: DevB,
data: [
{
Name: "John",
Source: "Home"
},
{
Name: "Alan",
Source: "Office"
},
{
Name: "Susan",
Source: "Office"
}
],
}
I tried the following code below. But it did not update it, neither gave an error.
collection1.update_one({ 'environment':'QA', 'data.Name':'Alan'},
{ $'set': {
"data":"Source":"NewValue"
}
})
environment: 'QA'so it would make sense that no update was performed if that was the data the operation was tested against. To your overall question - you'll probably want to look intoarrayFilterssince you want to manipulate thedataarray. See here$elemMatchhere if you are only searching a single field (Name) in thedataarray. You'd only need it if you added a second field in there. The second thing is to search for multiple names you probably want$in. So the second predicate should probably change to'data.Name': { $in: [ "Alan", "John" ] }