I want to find and update specific fields from mongodb using python(pymongo) Below is the exact structure of db
id: 2
Name: "CHK-MG-3"
NumberOfWorkbenches: 170
AllocatedWorkbenches: 0
Benchbetails: Array (17)
~ 0: Object
seatRowLabel: "A"
IsRowspace: false
~ seats: Array (13)
0: object
key: "A_1"
status: "available"
BenchName: ""
IsAllocated: True
IsRequested: false
seatNo: ""
seatLabel: ""
dir: ""
labelNo: "x12"
team: ""
AllocationData: Array (1)
0:Object
id:111
Program:"STL"
Duration:"3 days"
Team:"Frankestein"
First i want to find Name:"CHk-MG-3",then under the benchdetails, and inside seats(array) check for labelNo:x12 and update isallocatedto: false and AllocationData to None.
I think you can try this query using arrayFilters twice because the nested array:
With this query you are telling mongo:
Name
is CHK-MG-3
or has a property inside Benchbetails.seats.labelNo
with value x12
. Using this you can avoid to filter the entire collection into arrayFilters
stage.bench.seats.seat
is defined just below.bench
is the object in the Benchbetails
array where seats.labelNo
is x12
and seat
is the object into seats
array where labelNo
is x12
.So you are updating only the desired value into nested array setting IsAllocated
as False
and AllocationData
as None
.
collection.update_many(
{
"Name": "CHK-MG-3",
"Benchbetails.seats.labelNo": "x12"
},
{
"$set": {
"Benchbetails.$[bench].seats.$[seat].IsAllocated": False,
"Benchbetails.$[bench].seats.$[seat].AllocationData": None
}
},
array_filters=[
{"bench.seats.labelNo": "x12"},
{"seat.labelNo": "x12"}
]
)
Example here