5

I have such document in mongodb:

{uid:1212, outbox:
 [
   {msg1},
   {msg2},
   {msg3},
   ...
   {msgN}
 ]
}
I want atomically remove first n elements from array outbox.

I know two ways to remove element from array
1) $pop
  But it removes only one element
2) {$unset:{outbox.0:1}}  after {$pull:{outbox:null}}
  But it non atomic and removes only one element

Update This is impossible at the moment

1 Answer 1

5

I think you can do it like this:

db.data.update(
   {uid:1212}, 
   db.data.findOne({uid:1212}, {outbox: {$slice: [2,2]}, uid: 1, _id: 0 })
);

This would effectively replace the entire record with the new data, so you'd need to be a bit careful with it. You'd need to know the length of the outbox array to get the numbers right. That is, the $slice option will skip 2 records and then return the next two records in this case. There doesn't seem to be a way to skip two and then return the remaining items.

The first part, {uid:1212} limits the operation to that single document, and the second part returns the node but with a subset of those array elements, and is used as the data for the update.

More info on $slice here: http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements

Would that work for you?

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

Comments

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.