我正在使用 Mongoose 和 NodeJS (typescript)。 我正在尝试对每个位置的计数进行求和。示例输出:
[
{ name : "Bronx", count : 6 },
{ name : "Brooklyn", count : 6 },
{ name : "Manhattan", count : 6 },
{ name : "Queens", count : 6 }
]
Current data model:
data:
[
{
"news": {
"_id": "5c7615a4ef5238a6c47cbcb9",
"locations": [
{
"_id": "5c7615a4ef5238a6c47cbcc6",
"id": "1",
"name": "Manhattan",
"children": [
{
"_id": "5c7615a4ef5238a6c47cbcc8",
"count": 3
},
{
"_id": "5c7615a4ef5238a6c47cbcc7",
"count": 2
}
]
}
]
}
},
{
....
}
]
我构建的最后一个查询是:
DataModel.aggregate([
{ "$unwind": "$data.news.locations" },
{
"$group": {
"_id": "$data.news.locations",
"count": { "$sum": "$$data.news.locations.zipcodes.count" }
}
}]).exec(function(err, results){
if (err) throw err;
console.log(JSON.stringify(results, null, 4));
});
但是我是使用 Mongoose 处理 MongoDB 查询的新手,所以我非常感谢任何帮助。谢谢。
最佳答案
你们已经很接近了,只是做了一些改变:
DataModel.aggregate([
// Each array needs $unwind separately
{ "$unwind": "$data" },
// And then down to the next one
{ "$unwind": "$data.news.locations" },
// Group on the grouping key
{ "$group": {
"_id": "$data.news.locations.name",
"count": { "$sum": { "$sum": "$data.news.locations.children.count" } }
}}
],(err,results) => {
// remaining handling
})
因此,由于数组中有数组,并且您想要深入了解 “locations”
中的 "name"
属性,因此您需要 $unwind
到那时。您必须$unwind
每个数组级别分别。
从技术上讲,仍然存在 children
数组,但是 $sum
可用于"sum an array of values"以及“累积分组键”。因此 $group
中的 $sum: { $sum
语句.
返回:
{ "_id" : "Manhattan", "count" : 5 }
根据问题中提供的详细信息。
关于node.js - MongoDB 查询子文档中的不同内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54965552/