使用mongoose进行Mongodb查找+分组

时间:2016-09-24 23:35:52

标签: node.js mongodb mongoose

我有两个不同的猫鼬集合如下:

{ "_id" : 1, "countryId" : 1, "price" : 12, "quantity" : 24 }
{ "_id" : 2, "countryId" : 2, "price" : 20, "quantity" : 1 }
{ "_id" : 3  }
{ "_id" : 4, "countryId" : 1, "price" : 12, "quantity" : 24 }



{ "_id" : 1, "id" : 1, description: "Colombia"}
{ "_id" : 3, "id" : 2, description: "Mexic" }

我试图聚合它们,以便我可以得到如下结果:

{"country":"Colombia","total":48}
{"country":"Mexic","total":1}

我尝试了很多东西,但它总是在这里失败是我工作的最后一个版本(我已经改变了数据,但你明白了):< / p>

Model.aggregate([
      {
      $lookup:
        {
          from: "countryList",
          localField: "countryId",
          foreignField: "id",
          as: "country"
        },
       {
       $project: {
                    quantity:1, country:{$country:"$countryList.description"}
                 }
       },{
         $group:{
                 { _id : null, qtyCountry: { $sum: "$quantity" } }
         }
       }
   }],function (err, result) {
        if (err) {
            console.log(err);
        } else {
            console.log(result)
        }
    }
);

甚至可能吗?

1 个答案:

答案 0 :(得分:2)

是的,有可能。您可以尝试以下聚合管道。

var pipeline = [
                    {"$match":{"countryId":{"$exists":true}}},
                    {"$group" : {"_id":"$countryId", "quantity":{"$sum":"$quantity"}}}, 
                    {"$lookup":{"from":"countryList","localField":"_id", "foreignField":"id","as":"country"}}, 
                    {"$unwind":"$country"}, 
                    {"$project": {"country":"$country.description", "total":"$quantity", _id:0}}
                ]

示例输出:

{ "country" : "Mexic", "total" : 1 }
{ "country" : "Colombia", "total" : 48 }