MongoDB Aggregation: Counting distinct fields -
i trying write aggregation identify accounts use multiple payment sources. typical data be.
{ account:"abc", vendor:"amazon", } ... { account:"abc", vendor:"overstock", }
now, i'd produce list of accounts similar this
{ account:"abc", vendorcount:2 }
how write in mongo's aggregation framework
i figured out using $addtoset , $unwind operators.
mongodb aggregation count array/set size
db.collection.aggregate([ { $group: { _id: { account: '$account' }, vendors: { $addtoset: '$vendor'} } }, { $unwind:"$vendors" }, { $group: { _id: "$_id", vendorcount: { $sum:1} } } ]);
hope helps someone
Comments
Post a Comment