Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "$count" Within an "addField" Operation in MongoDB Aggregation

Tags:

count

mongodb

I am trying to find the correct combination of aggregation operators to add a field titled "totalCount" to my mongoDB view.

This will get me the count at this particular stage of the aggregation pipeline and output this as the result of a count on each of the documents:

    {
        $count: "count"
    }

But I then end up with one document with this result, rather than what I'm trying to accomplish, which is to make this value print out as an addedField that is a field/value on all of the documents, or even better, a value that prints in addition to the returned documents.

I've tried this but it gives me an error ""Unrecognized expression '$count'",":

    {
        $addFields: {
          "totalCount" : { $count: "totalCount" }
        }
    }

What would the correct syntactical construction be for this? Is it possible to do it this way, or do I need to use $sum, or some other operator to make this work? I also tried this:

    {
        $addFields: {
          "totalCount" : { $sum: { _id: 1 } }
        }
    },

... but while it doesn't give me any errors, it just prints 0 as the value for that field on every document rather than the total count of all documents.

like image 850
Muirik Avatar asked Jun 25 '18 18:06

Muirik


1 Answers

Total count will always be a one-document result so you need $facet to run mutliple aggregation pipelines and then merge results. Let's say your regular pipeline contains simple $project and you want to merge it's results with $count. You can run below aggregation:

db.col.aggregate([
    {
        $facet: {
            totalCount: [
                { $count: "value" }
            ],
            pipelineResults: [
                {
                    $project: { _id: 1 } // your regular aggregation pipeline here 
                }
            ]
        }
    },
    {
        $unwind: "$pipelineResults"
    },
    {
        $unwind: "$totalCount"
    },
    {
        $replaceRoot: {
            newRoot: {
                $mergeObjects: [ "$pipelineResults", { totalCount: "$totalCount.value" } ]
            }
        }
    }
])

After $facet stage you'll get single document like this

{
    "totalCount" : [
        {
            "value" : 3
        }
    ],
    "pipelineResults" : [
        {
            "_id" : ObjectId("5b313241120e4bc08ce87e46")
        },
        //....
    ]
}

Then you have to use $unwind to transform arrays into multiple documents and $replaceRoot with $mergeObjects to promote regular pipeline results into root level.

like image 70
mickl Avatar answered Nov 08 '22 14:11

mickl