user1855877
user1855877

Reputation: 81

Mongodb array manipulation

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.

Upvotes: 3

Views: 509

Answers (1)

Norbert Pisz
Norbert Pisz

Reputation: 3440

To change object value use $set:

'$set':{quantity: 1}

For increment you can use $inc

$inc: { quantity: 5 } 

To add new item in array use $push:

$push: { quantity: 0 }

Chek all array operations here: Array Update Operators

Upvotes: 2

Related Questions