I am new to MongoDB and not able to generate a query to update items in a list based on the item names.
My example object is:
Inventory:
{ _id: "1234",
name: "test",
items: [
{ "name": "pen", "count": 4}, {"name": "copy", "count": 10}, {"name": "book", "count": 2}
]
}
{ _id: "4567",
name: "test2",
items: [
{ "name": "pen", "count": 1}, {"name": "copy", "count": 1}, {"name": "book", "count": 10}
]
}
I want to update the data based on the inventory id and the name of the item. Update can be for multiple items but only for 1 inventory.
Example Update request:
{ _id: “1234”,
data: { “pen”: 1, “copy”:-5}
}
And the result Inventory should be:
{ _id: "1234",
name: "test",
items: [
{ "name": "pen", "count": 5}, {"name": "copy", "count": 5}, {"name": "book", "count": 2}
]
}
I tried and created a query, but facing issue to make it dynamic:
def _prepare_query(data):
update_query = {
"$set": {
"items": {
"$map": {
"input": "$items",
"as": "item",
"in": {
"$cond": [
{"$eq": ["$$item.name", {"$in": list(data.keys())}]},
{
"name": "$$item.name",
"count": {
"$inc": ["$$item.count", data["$$item.name"]]
},
},
"$$item",
]
},
}
}
}
}
where, data is the input dict
data: { "pen": 1, "copy":-5}
This is throwing KeyError: “$$item.name”, which is obv as data doesn’t have a key with that string.
Can I not prepare the query outside the db.collection.updateOne() call?
Any help would be appreciated.
Thanks