Search code examples
mongodbspring-bootaggregate

MongoDb aggregate executing two times only to count my records


i've one question about find pageable and count my records in aggregate at same time, in my case i've this two aggregate:

This one is only to find records limited and pageables:

db.myCollection.aggregate([
             { $match : { ... }}, 
             { $project : { .. }}, 
             { $group : {... }},
             { $sort  : {... }},
             { $limit : 10}, { $skip : 10}])

And this other is only to count the amounts of records filtered and grouped whitout pageable:

db.myCollection.aggregate([
             { $match : { ... }}, 
             { $project : { .. }}, 
             { $group : {... }},
             { $count : "amount" }])

But i've a large database and this both aggregation is costly, so my question is: Could i get my records and count at the same time?


Solution

  • I've reached results with facet, i've insert facets after the group:

    { $group : {... }},
    { $facet : {
      "data" : [{
          $project : { 
            _id : "$_id", 
            foo  : "$foo"
          }  
        }]}
    },
    {
      $project : {
          "amount" : { $size : "$data" },
          data : "$data"
      }},
    { 
      $unwind : {
           path: "$data"
     }},
    
    { $project : 
        {
            "amount" : 1,
            _id : "$data._id", 
             foo : "$data.foo"
         }
    }
    

    After this 4 operations i've the all datas with the amount of datas too.