MongoDB Aggregation: Counting distinct fields

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

    An example

    db.collection.distinct("example.item").forEach( function(docs) {
        print(docs + "==>>" + db.collection.count({"example.item":docs}))
    });
    
    0 讨论(0)
  • 2020-12-13 05:32

    To identify accounts that use multiple payment sources:

    1. Use grouping to count data from multiple account records and group the result by account with count
    2. Use a match case is to filter only such accounts having more than one payment method
      db.payment_collection.aggregate([ { $group: {"_id":"$account" ,
     "number":{$sum:1}} }, {
                         "$match": {
                             "number": { "$gt": 1 }
                          }
                     } ])
    

    This will work perfectly fine,

    0 讨论(0)
提交回复
热议问题