Home > Enterprise >  mongo - get count of a intermediary document
mongo - get count of a intermediary document

Time:06-13

currently I have a query:

const result = await getInstances();

that provides me an array of document:

[{name: "first", age: 13},
{name: "second", age: 21},
{name: "third", age: 11},
{name: "fourth", age: 14}
...]  

The query goes something like this:

...
return Instances.aggregate
         .match({//condition})
         .skip(skipValue).limit(pageSize) // pagination done here

I want a query that appends a count for the total no. of documents before the pagination, but returns the paginated data, e.g:

...
return Instances.aggregate
         .match({//condition}) ## I WANT THE COUNT OF THIS STEP TO BE APPENDED
         .<SOME_PIPELINE_HERE>
         .skip(skipValue).limit(pageSize) // pagination done here
  

would return something like:

{
  data: [{name: "first", age: 12}....<ALL_PAGINATED_DATA>],
  totalCount: 54  #count of data before pagination
}

What I tried and didn't work:

Instances.aggregate()
  .match({//CONDITION})
  .addFields({count: {$size: _id}})
  .skip(value).limit(value)

It seems it goes through and calculates this for each document instead of the whole

CodePudding user response:

One option is to use $facet in order to "fork" the query in the middle, so the same data can be used on different pipelines. For example:

db.collection.aggregate([
  {$match: {a: {$in: [7, 8, 9]}}},
  {
    $facet: {
      total: [{$group: {_id: null, count: {$sum: 1}}}],
      data: [{$skip: 1}]
    }
  },
  {$project: {data: 1, total: {$first: "$total.count"}}}
])

See how it works on the playground example

  • Related