Distinct count of multiple fields using mongodb aggregation

℡╲_俬逩灬. 提交于 2019-12-03 14:43:07

You're looking for the power of ... $objectToArray!

db.foo.aggregate([
  {$project: {x: {$objectToArray: "$$CURRENT"}}}
  ,{$unwind: "$x"}
  ,{$match: {"x.k": {$ne: "_id"}}}
  ,{$group: {_id: "$x.k", y: {$addToSet: "$x.v"}}}
  ,{$addFields: {size: {"$size":"$y"}} }
                    ]);

This will yield:

{ "_id" : "num_doors", "y" : [ 4 ], "size" : 1 }
{ "_id" : "color", "y" : [ "blue", "red" ], "size" : 2 }
{
    "_id" : "car_type",
    "y" : [
        "wagon",
        "hatchback",
        "suv"
    ],
    "size" : 3
}

You can $projector $addFieldsas you see fit to include or exclude the set of unique values or the size.

Running the following aggregate pipeline should give you the desired result:

db.collection.aggregate([
    {
        "$group": {
            "_id": null,
            "distinct_car_types": { "$addToSet": "$car_type" },
            "distinct_colors": { "$addToSet": "$color" },
            "distinct_num_doors": { "$addToSet": "$num_doors" }
        }
    },
    {
        "$project": {
            "distinct_count_car_type": { "$size": "$distinct_car_types" },
            "distinct_count_color": { "$size": "$distinct_colors" },
            "distinct_count_num_doors": { "$size": "$distinct_num_doors" }
        }
    }
])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!