MongoDB Aggregation: Counting distinct fields

前端 未结 8 2114
礼貌的吻别
礼貌的吻别 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:29

    I think its better if you execute query like following which will avoid unwind

    db.t2.insert({_id:1,account:"abc",vendor:"amazon"});
    db.t2.insert({_id:2,account:"abc",vendor:"overstock"});
    
    
    db.t2.aggregate(
    { $group : { _id : { "account" : "$account", "vendor" : "$vendor" }, number : { $sum : 1 } } },
    { $group : { _id : "$_id.account", number : { $sum : 1 } } }
    );
    

    Which will show you following result which is expected.

    { "_id" : "abc", "number" : 2 }
    

提交回复
热议问题