0

Is there a way to remove certain amounts of elements from start of an array in MongoDB?

Suppose I don't know about element's details (like id or uuid) but I know that I want to remove the first N elements from the start of it. Is there a way to do it in mongoDB? I know I can fetch the whole document and process it in my own programming language environment but I thought it would be nicer if mongoDB already implemented a way to achieve it atomically by its own query language.

2 Answers 2

1

There is a $pop operator to remove a single element from the array either from top or bottom position,

and there is a closed jira support request SERVER-4798 regarding multiple pop operations, but in comment they have suggested to use update with aggregation pipeline option.

So you can try update with aggregation pipeline starting from MongoDB 4.2,

  • $slice, pass negative number and it will slice elements from 0 index
let n = 2;
db.collection.updateOne(
  {}, // your query
  [{
    $set: { arr: { $slice: ["$arr", -n] } }
  }]
)

Playground

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

1 Comment

Thanks but it only works if you already know the array's length. As you can see in playground, It does not work if length is 5 or more.
0

What @turivishal metioned is true however it only works if array's size is always 4. For it to work for all array sizes we should consider size of the array in aggregation, so:

let n = 2;
db.collection.update({},
[
  {
    $set: {
      arr: {
        $slice: [
          "$arr",
          {
            $subtract: [
              -n,
              {
                $size: "$arr"
              }
            ]
          },
          
        ]
      }
    }
  }
])

Playground

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.