如何删除数组中除第一个索引之外的所有内容?

Jak*_*son 2 mongodb

我有一个收藏people。它有一个数组字段numbers,其中每个文档在所述数组中都有不同数量的元素。

我的目标是保留第 0 个索引中的元素并递归删除其余元素。我该怎么做呢?

例如:

{_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]},
Run Code Online (Sandbox Code Playgroud)

Cla*_*oft 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 } } }
);
Run Code Online (Sandbox Code Playgroud)

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

See this on Mongo Playground.