Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove first n elements from mongodb array?

Tags:

mongodb

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

like image 924
terbooter Avatar asked Mar 16 '12 07:03

terbooter


1 Answers

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?

like image 118
Mick Sear Avatar answered Oct 12 '22 00:10

Mick Sear