How to remove the first n elements from a mongodb array?

I have a document like this 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 not currently possible.

+4
source share
1 answer

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 will effectively replace the entire record with new data, so you will need to be a little careful with it. You need to know the length of the outgoing message array in order to get the correct numbers. That is, the $ slice option skips 2 entries, and then returns the next two entries in this case. There seems to be no way to skip two and then return the rest of the elements.

The first part, {uid: 1212} restricts the operation for this single document, and the second part returns node, but with a subset of these array elements, it is used as data for updating.

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

Will this work for you?

+4
source

Source: https://habr.com/ru/post/1401749/


All Articles