How do you return multiple results from a mongoDB aggregate () query?

Here's a query that performs a match and then returns the number of unique records in a specific field:

db.sequences.aggregate([{$match: {id: 5}}, {$group : {_id : "$field"} }, {$group: {_id:1, count: {$sum : 1 }}}])

      

However, what if I wanted to return multiple values, such as the number of all documents in the original match match, the first 50 documents in the original match, and the number of unique field2 records for the same matched document set?

Can I write 1 aggregate query that returns all of these values?

+3


source to share


1 answer


You need to do two separate steps $group

. First $group

in the field filed

, and then the $push

resulting documents into an array and at the same time we accumulate count

from each document to get the total amount.



db.sequences.aggregate(
   [
      {$match: {id: 5}}, 
      {$group : 
         {
            _id : "$field", 
            count: {$sum: 1}
         }
      },
      {$group : 
         {
            _id : null, 
            totalNumberOfMatches: {$sum: '$count'},
            totalNumberOfUniqueMatches: {$sum: 1},
            uniqueMatchesField:
               {
                  $push:
                     {
                        field: '$_id',
                        count: '$count'
                     }
               }
         }
      },
   ]
)

      

+3


source







All Articles