MongoDB Aggregation: Counting distinct fields

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

    This approach doesn't make use of $unwind and other extra operations. Plus, this won't affect anything if new things are added into the aggregation. There's a flaw in the accepted answer. If you have other accumulated fields in the $group, it would cause issues in the $unwind stage of the accepted answer.

    db.collection.aggregate([{
        "$group": {
            "_id": "$account",
            "vendors": {"$addToSet": "$vendor"}
        }
    },
    {
        "$addFields": {
            "vendorCount": {
                "$size": "$vendors"
            }
        }
    }])
    

提交回复
热议问题