Reputation: 51
{
"Department" : "PE",
"Staff" : [
{
"Name" : "Allen",
"Designation" : "Application Developer",
"Leaves" : 10
},
{
"Name" : "Allen",
"Designation" : "Product Developer",
"Leaves" : 10
},
{
"Name" : "Billy",
"Designation" : "Product Developer",
"Leaves" : 10
},
{
"Name" : "Bob",
"Designation" : "Application Developer",
"Leaves" : 10
},
{
"Name" : "Bob",
"Designation" : "Product Developer",
"Leaves" : 10
},
{
"Name" : "Jim",
"Designation" : "Application Developer",
"Leaves" : 10
},
{
"Name" : "Han",
"Designation" : "Salesforce Developer",
"Leaves" : 10
}
]
}
I have a Document with the above structure in MongoDB. I am trying to update Leaves
value to 15 having Designation as Application Developer and Product Developer. I tried this query
updateOne({'$and': [{"Department" : "PE"}, {'Staff.Name': Name}, {'Staff.Designation': Designation}]},{"$set": {'Staff.$.Leaves': 15}}, upsert=True)
OR
updateOne({"Department" : "PE", 'Staff.Name': Name, 'Staff.Designation': Designation},{"$set": {'Staff.$.Leaves': 15}}, upsert=true)
Output:
updated:2 {
"Name" : "Allen",
"Designation" : "Application Developer",
"Leaves" : 15
},
{
"Name" : "Allen",
"Designation" : "Product Developer",
"Leaves" : 15
}
Not updated: 5
I tried the below queries:
updateOne({'$and': [{"Department" : "PE"}, {'Staff.Name': Name}, {'Staff.Designation': Designation}]},{"$set": {'Staff.$[].Leaves': 15}}, upsert=true) --> Throwing exception
updateOne({'$and': [{"Department" : "PE"}, {'Staff.Name': Name}, {'Staff.Designation': Designation}]},{"$push": {'Staff.$.Leaves': 15}}, upsert=true) --> Not working
updateOne({'$elemMatch': {"Department" : "PE", 'Staff.Name': Name, 'Staff.Designation': Designation}},{"$set": {'Staff.$.Leaves': 15}}, upsert=true) --> Throwing exception
Upvotes: 1
Views: 87
Reputation: 36114
You need to use arrayFilters, The filtered positional operator $[<identifier>]
identifies the array elements that match the arrayFilters conditions for an update operation,
updateOne(
{ "Department": "PE" },
{
"$set": {
"Staff.$[s].Leaves": 15
}
},
{
arrayFilters: [
{
"s.Designation": {
$in: ["Application Developer", "Product Developer"]
},
"s.Name": "Allen"
}
],
upsert: true
}
)
Upvotes: 1