I've problem with array manipulation in mongodb. I will show on example what I need.
My collection structure:
{ id: "user1", items: [ { id: "1", quantity: 1 }, { id: "2", quantity: 3 } ] }
{ id: "user2", items: [ { id: "1", quantity: 1 }, { id: "3", quantity: 3 } ] }
I would like add some items for user1.
If items with id exist already in user array I would like to just increment quantity. If not I would like add it to items list.
In example:
I would like to add items [ { id: "1", quantity: 1 }, { id: "3", quantity: 1 } ] for user1
After this operation structure of collection should look like:
{ id: "user1", items: [ { id: "1", **quantity: 2** }, { id: "2", quantity: 3 }, **{ id: "3", quantity: 1 }** ] }
{ id: "user2", items: [ { id: "1", quantity: 1 }, { id: "3", quantity: 3 } ] }
How to do it? Aggregation? Map reduce? I don't want to make query for each of added element.
$setand$pushoperators of MongoDB