MongoDB Aggregation: Counting distinct fields

前端 未结 8 2237
礼貌的吻别
礼貌的吻别 2020-12-13 04:33

I am trying to write an aggregation to identify accounts that use multiple payment sources. Typical data would be.

{
 account:\"abc\",
 vendor:\"amazon\",
}         


        
8条回答
  •  执笔经年
    2020-12-13 05:30

    You can use sets

    db.test.aggregate([
        {$group: { 
          _id: "$account", 
          uniqueVendors: {$addToSet: "$vendor"}
        }},
        {$project: {
          _id: 1, 
          vendorsCount: {$size: "$uniqueVendors"}
        }}
    ]);
    

提交回复
热议问题