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.
source share