Home > Enterprise >  How to get totalCount and first document in a single MongoDB query result?
How to get totalCount and first document in a single MongoDB query result?

Time:06-14

There is a filter myFilter used to get some insights about the xyz collection. Now I need to run three queries having the same step for filtering the documents

db.xyz.find(myFilter).sort(mySort1).limit(1) // get first item by sort #1
db.xyz.find(myFilter).sort(mySort2).limit(1) // get first item by sort #2
db.xyz.find(myFilter).count()                // get total count

How to express the same intention in a single query or aggregation?

Expected result is

{
  "item_1": {/* first doc by (myFilter & mySort1) *//},

  "item_1": {/* first doc by (myFilter & mySort2) *//},

  "totalCount": /* count of all by myFilter */
}

CodePudding user response:

You can use $facet to run several pipelines on the same data at one query:

db.collection.aggregate([
  {$match: myFilter}
  {$facet: {
    item_1: [{sort1}],
    item_2: [{sort2}],
    totalCount: [{$group: {_id: null, count: {$sum:1}}}]
  }}
])
  • Related