MongoDB Aggregation: Counting distinct fields

aggregation-framework, mongodb

Solution

I figured this out by using the $addToSet and $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 it helps someone

Problem

I am trying to write an aggregation to identify accounts that use multiple payment sources. Typical data would be. ``` { account:"abc", vendor:"amazon", } ... { account:"abc", vendor:"overstock", } ``` Now, I'd like to produce a list of accounts similar to this ``` { account:"abc", vendorCount:2 } ``` How would I write this in Mongo's aggregation framework

Original source

Related problems