1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| demo data: db.getCollection('test111').insert([ {"orderID" : "30688", "region" : "CO", "customerID" : "11396783", "productID" : "13001"}, {"orderID" : "30688", "region" : "CO", "customerID" : "11396783", "productID" : "8002"}, {"orderID" : "30688", "region" : "CO", "customerID" : "11396783", "productID" : "5001"}, {"orderID" : "89765", "region" : "CA", "customerID" : "54157526", "productID" : "7412"}, {"orderID" : "89765", "region" : "CA", "customerID" : "54157526", "productID" : "5198"}, {"orderID" : "21546", "region" : "KA", "customerID" : "20103585", "productID" : "6851"}, {"orderID" : "21546", "region" : "KA", "customerID" : "20103585", "productID" : "7412"}, {"orderID" : "21546", "region" : "KA", "customerID" : "20103585", "productID" : "6987"}, {"orderID" : "21794", "region" : "NY", "customerID" : "78125522", "productID" : "13001"}, ]) example: SQL Query: (group by & count of distinct)
select city,count(distinct(emailId)) from TransactionDetails group by city; Equivalent mongo query would look like this:
db.TransactionDetails.aggregate([ {$group:{_id:{"CITY" : "$cityName"},uniqueCount: {$addToSet: "$emailId"}}}, {$project:{"CITY":1,uniqueCustomerCount:{$size:"$uniqueCount"}} } ]); exercise: db.getCollection('tal_7-7_step4').aggregate([ {"$group": {_id: {"region":"$region"}, "uniqueCount": {"$addToSet": "$orderID"}}}, {"$project":{"region":1,"unique_count":{$size:"$uniqueCount"}}} ]);
db.getCollection('xx').aggregate([ { "$match": { "ts_short": { "$gte": "2021-02-22", "$lte": "2021-02-24" } } }, { "$match": { "data": { "$exists": true } } }, { "$group": { "_id": { "city_name": "$city_name" }, "uniqueCount": { "$addToSet": "$cla_id" } } }, { "$project": { "city_name": 1, "unique_count": { "$size": "$uniqueCount" } } } ])
|