0

I am unable to get both the number of total hits and data in the documents in one aggregation query. My aggregation pipeline looks like this:

{
    '$match': {
        'some_text': 'Stackoverflow', 
        'some_status': 1
    }
}, 
{
    '$count': 'hits'
}

All I get after the second stage is hits = N. Just 1 document giving the total number of documents matched. I'd like the pipeline to return other details as well, but according to the mongo docs "$count" stage returns a new document to the next stage of the pipeline. How can I use hits value at a later stage of the pipeline and get all document data also.

Desired result:

{
    "hits": 20,
    "data": [
        {
            "name": "Name1",
            "age": 10
        },
        {
            "name": "Name2",
            "age": 23
        }
    ]
}

Thanks.

yugantar
  • 1,970
  • 1
  • 11
  • 17
  • 1
    Either use another `.count()` query to count the matching criteria or use [`$facet`](https://docs.mongodb.com/manual/reference/operator/aggregation/facet/) aggregation to process the multiple aggregation within a single query – Ashh Jan 30 '19 at 16:59
  • If I use .count() then it means I'll have to use 2 queries again. $facet seems to work well for me so thanks for that. I am not sure if this is the best way I can get the desired result, would love to know a better approach than this if there is one. – yugantar Jan 30 '19 at 17:18
  • `.count()` queries are always cheaper ones. So *to use 2 queries again* this should not matter because it always works better than a `aggregate` query. Even if you want to do with single query have a look here https://stackoverflow.com/a/53220591/7510657 – Ashh Jan 30 '19 at 17:24

0 Answers0