Home > Software engineering >  How to delete everything in an array except the first index?
How to delete everything in an array except the first index?

Time:05-23

I have a collection people. It has an array field numbers, where each document has a varying number of elements in said array.

My goal is to keep the elements in the 0th index and recursively remove the rest. How could I go about doing this?

For example:

{_id: 1, numbers: [100, 200, 300]},       ->   {_id: 1, numbers: [100]},
{_id: 2, numbers: [101, 201]},            ->   {_id: 2, numbers: [101]}
{_id: 3, numbers: [102, 202, 400, 500]},  ->   {_id: 3, numbers: [102]},

CodePudding user response:

An alternative solution to @R2D2 is to use $slice. Unlike $first, $slice works for more than one element.

collection.updateMany(
  {},
  { $push: { numbers: { $each: [], $slice: 1 } } }
);

You could also use $slice: -1 to start from the last element.

See this on Mongo Playground.

CodePudding user response:

You can use the operator $first in update pipeline as follow:

 db.collection.update({},
 [
  {
   $addFields: {
     numbers: {
       $first: "$numbers"
       }
     }
  }
],
{
 multi: true
 })

Explained:

Replace the "numbers" array in all documents with array with only the first element taken from "numbers"

Playground

If you want the "numbers" to be still of type array you can enclose the output from $first in square brackets [] as follow:

     numbers: [{
       $first: "$numbers"
       }]

Playground 2

Btw , $first is alias of $arrayElemAt that you can use to extract other elements from the array ...

But afcourse the operation can be done via $slice as mentioned earlier by @Clashsoft

  • Related