Variable number of multiple fields using mongodb aggregation

I am trying to count the various values ​​of several fields. One MongoDB aggregation request.

So here are my details:

{ "car_type": "suv", "color": "red", "num_doors": 4 }, { "car_type": "hatchback", "color": "blue", "num_doors": 4 }, { "car_type": "wagon", "color": "red", "num_doors": 4 } 

I need a separate counter for each field:

 distinct_count_car_type=3 distinct_count_color=2 distinct_count_num_doors=1 

I managed to group several fields and then make a clear count, but it can only give me a count of the first field. Not all of them. It is also a large data set.

+5
source share
2 answers

You seek power ... $objectToArray !

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

This will give:

 { "_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 $project or $addFields as you see fit to include or exclude a set of unique values ​​or size.

+1
source

Starting the next aggregate conveyor 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" } } } ]) 
+4
source

Source: https://habr.com/ru/post/1272197/


All Articles