MongoDB aggregation: transform list of documents into list

27 Views Asked by At

I have this documents:

[ { id: 1 }, {id: 2}, {id: 3} ]

I want to transform that into:

{ ids: [1, 2, 3] }

or

[1, 2, 3]

Which is the most efficient pipeline for that?

Thanks!

1

There are 1 best solutions below

0
Vajilo Toram On BEST ANSWER

You can use $group and $project stage.

For the first result - { ids: [1, 2, 3] }, please use the following MongoDB aggregation pipeline.

[
  {
    $group: {
      _id: null,
      ids: { $push: "$id" }
    }
  },
  {
    $project: {
      _id: 0,
      ids: 1
    }
  }
]

You can get desired result only use $group stage in above pipeline, but there is a field _id: null, so you can remove this field using $project stage.