Using “$count” Within an “addField” Operation in MongoDB Aggregation

六眼飞鱼酱① 提交于 2020-02-19 05:47:11

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/51029987/using-count-within-an-addfield-operation-in-mongodb-aggregation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!