Home > Software engineering >  MongoDB: Remove elements from start of an array
MongoDB: Remove elements from start of an array

Time:10-03

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.

CodePudding user response:

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

  • Related