2

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]},
2
  • 1
    See mongodb.com/docs/manual/reference/operator/update/slice. Maybe something like { $push: { numbers: { $each: [], $slice: 1 } } } could work. $slice: -1 would keep only the last element. Commented May 22, 2022 at 9:33
  • @Clashsoft That is perfect, thank you. Feel free to create a proper Answer, otherwise I will. Commented May 22, 2022 at 9:46

2 Answers 2

5

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.

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

Comments

1

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

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.