Home > Software design >  Is it possible to delete the firsts elements in an array?
Is it possible to delete the firsts elements in an array?

Time:04-25

I'm coding an application, and in one of the parts of the code I need to delete a certain amount of elements from an array, but I don't have much experience with MongoDB/Mongoose.

For example, my query needs to delete the first n elements of an array:

let array = ["a", "b", "c", "d", "e"];

if (n < array.length) {
    array = array.slice(n); // Delete the first n values
}

I could loop my code, but it will do a lot of queries, deleting one by one, which is bad for performance. My other alternative is to query the array elements, slice in the code, and update the database array with another query. It's also a good alternative, but I prefer to ask here because maybe there is a way to do it with just one query.

I know in MongoDB there is a way to just remove the first/last element, but I haven't found anything about deleting more than one.

Model.updateOne(filter, { $pop: { list: -1 } });

CodePudding user response:

Hey you can check out the $slice operator when you query. That said, it works well, if you're removing multiple elements from the end or multiple elements from the start of the array. But if you're removing from the middle of the array, it may be easier to find the document first, apply a standard .slice() operation in JavaScript, and then save the document with the new array, by calling the .save() method on the document.

As examples for the $slice operator:

const document = { "_id" : 3, "scores" : [  89,  70,  100,  20 ] }
    db.students.update(
      { _id: 3 },
      {
        $push: {
          scores: {
             $each: [ ],
             $slice: -2
          }
        }
      }
    )
/*
Our result is the last two elements, and we removed the first two. 
*/
const result = { "_id" : 3, "scores" : [ 100,  20 ] }

Or you can something like the following:

db.students.update({_id: 3}, [
     {$set: {scores: {
          $slice: ["$field", {$add: [1, P]}, {$size: "$field"}]
     }}}
]);

Where P is the index of element you want to stop removing in the array, leaving you with P to the end elements. (meaning all elements prior to P are removed)

Or this:

db.students.update({_id: 3}, [
     {$set: {scores: {
         $slice: ["$field", P]
}}}
]);

Where P is the index of element you want to stop removing in the array from the end, leaving you with start to P elements. (meaning all elements after P are removed)

  • Related