0

I want to delete the last 2 elements from an array object.

{
    "_id" : ObjectId("597973c8c9fadd14e8ea51bb"),
    "values" : [1,2,3,4,5,6]
}

I have tried $pop but it delete only one element each time. Is there any convenient way?

1
  • There are other ways, but the general presumptions are based on having some foreknowlege of the number of items in the array. For instance if you know you want to reduce the array to 4 items in total you can do that, or if you wanted to keep only 6 items in total whilst adding new items, then you can do that as well. In brief there is likely a better solution to a "real use case" as opposed to the trivial one you are presenting. So perhaps if you described the reason why you really want to do it, then you could be presented with a better solution. Commented Aug 22, 2017 at 3:51

1 Answer 1

1

There's no way to do this as far as I know. The closest you can do would probably to get the list in your application ($slice to make it smaller if you prefer), put the last n items in an array and do a $pull. It'll pull all similar elements though.

If that's not an option, repeating $pop seems to be the only way.

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.