Search code examples
javascriptnode.jsmongodbmongooseaggregate

MongoDB - How to return matching documents and number of matching documents in array of object


I'm struggling to write a mongo aggregation which will return both the matching documents, as well as the number of matching documents for each identifier (in this example, staffId).

I have the following aggregation which works to return the count, but I can't seem to get the matching documents for each staffId.

xxx.aggregate([
       // step 1
      {
        $match: obj,
      },
      // step 2
      {
        $group: {
          _id: "$staffId",
          count: { $sum: 1 },
        },
      },
    ]);

The idea being that this will return an array of objects with the staffId and count. I then want to use each staffId to return the matching documents, to return something like:

[{_id: '1234', count: 4, documents: [matching-documents for staff 1234]}, {_id: '5678', count: 12, documents: [matching-documents for staff 5768] } ]

Any help is massively appreciated. Thanks!


Solution

  • You can $push the $$ROOT, which refers to the document it self in the $group stage.

    db.collection.aggregate([
      {
        $group: {
          _id: "$staffId",
          count: {
            $sum: 1
          },
          documents: {
            $push: "$$ROOT"
          }
        }
      }
    ])
    

    Mongo Playground