javascriptarraysmongodbpaginationaggregates

MongoDB group $ROOT (collection) document items as key value pairs in the new field


consider the following array of documents returned from the aggregation:

[
  {
    id: '#abcdefg123',
    title: 'Doc 1'
    ...
  },
  {
    id: '#abcdefg124',
    title: 'Doc 2'
    ...
  },
  {
    id: '#abcdefg125',
    title: 'Doc 3'
    ...
  }
]

Each document contains like 20 fields...

I would like to get the following output:

{
  edges: [
    {
      node: {
        id: '#abcdefg123',
        title: 'Doc 1',
        ...
      }
      cursor: '#abcdefg123'
    },
    {
      node: {
        id: '#abcdefg124',
        title: 'Doc 2',
        ...
      }
      cursor: '#abcdefg124'
    },
    {
      node: {
        id: '#abcdefg125',
        title: 'Doc 3',
        ...
      }
      cursor: '#abcdefg125'
    }
  ]
}

I've tried to $group a new field edges with $push as k, v pair of '$ROOT' but with no such desired result. And I've tried to use $map on something like '$$ROOT' as input and trying to return object

{
  node: '$item',
  cursor: '$item._id'
}

Of course with not luck either.

I don't want to iterate over the results and populate the right object shape of data after the aggregation. Considering the performance would drop.

I would prefer to achieve the desired result inside of aggregation pipeline.

Thanks in advance.


Solution

  • db.collection.aggregate([
      {
        $project: {
          "node": "$$ROOT",
          "cursor": "$id"
        }
      },
      {
        $group: {
          "_id": null,
          "edges": {
            $push: "$$ROOT"
          }
        }
      }
    ]);
    

    Mongo Playground