MongoDB distinct aggregation

前端 未结 4 569
粉色の甜心
粉色の甜心 2020-12-08 06:43

I\'m working on a query to find cities with most zips for each state:

db.zips.distinct(\"state\", db.zips.aggregate([ {$group:{_id:{state:\"$state\", city:\"         


        
相关标签:
4条回答
  • 2020-12-08 07:08

    You can use $addToSet with the aggregation framework to count distinct objects.

    For example:

    db.collectionName.aggregate([{
        $group: {_id: null, uniqueValues: {$addToSet: "$fieldName"}}
    }])
    
    0 讨论(0)
  • 2020-12-08 07:19

    Distinct and the aggregation framework are not inter-operable.

    Instead you just want:

    db.zips.aggregate([ 
        {$group:{_id:{city:'$city', state:'$state'}, numberOfzipcodes:{$sum:1}}}, 
        {$sort:{numberOfzipcodes:-1}},
        {$group:{_id:'$_id.state', city:{$first:'$_id.city'}, 
                  numberOfzipcode:{$first:'$numberOfzipcodes'}}}
    ]);
    
    0 讨论(0)
  • 2020-12-08 07:25

    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"}} } 
    ]);
    
    0 讨论(0)
  • 2020-12-08 07:31

    You can call $setUnion on a single array, which also filters dupes:

    { $project: {Package: 1, deps: {'$setUnion': '$deps.Package'}}}
    
    0 讨论(0)
提交回复
热议问题