gpt4 book ai didi

node.js - Mongodb 查找 + 使用 mongoose 进行分组

转载 作者:太空宇宙 更新时间:2023-11-04 03:06:29 25 4
gpt4 key购买 nike

我有两个不同的 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}

我尝试了很多东西,但总是失败,这是我正在开发的最后一个版本(我已经更改了数据,但你明白了):

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

这可能吗?

最佳答案

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

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 }

关于node.js - Mongodb 查找 + 使用 mongoose 进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39681954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com