How to make nested queries in MongoDb that works like nested Sql select queries

前端 未结 6 1189
不知归路
不知归路 2021-02-05 11:02

I want to make an efficient query in MongoDb to find all users who have their userids listed in a usergroup. Ideally I want to make this as a single request to Mongodb. What I w

6条回答
  •  半阙折子戏
    2021-02-05 11:34

    -sUReN

    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"}} } 
    ]);
    

提交回复
热议问题