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
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With