3

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.

2
  • Look at the $set and $push operators of MongoDB Commented Dec 10, 2013 at 10:19
  • Thanks for answer. I can use pushAll to add everything by one query to array. But then it will look like: { id: "user1", items: [ { id: "1", quantity: 1 }, { id: "2", quantity: 3 }, { id: "3", quantity: 1 }, { id: "1", quantity: 1 } ] }. That's not that I need. Commented Dec 10, 2013 at 10:25

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Ye, thanks. I know that I can do it from N [just inc] to 2*N [checking if can inc - if not already in array then push] queries (where N is length of pushed array). Just wonder if I can do it by less work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.