node.js - 子文档中不同的 MongoDB 查询
问题描述
我将 Mongoose 与 NodeJS(打字稿)一起使用。我正在尝试对每个位置的计数求和。示例输出:
[
{ name : "Bronx", count : 6 },
{ name : "Brooklyn", count : 6 },
{ name : "Manhattan", count : 6 },
{ name : "Queens", count : 6 }
]
当前数据模型:
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
})
因此,由于您在数组中有数组,并且您想深入了解其中的"name"
属性,因此"locations"
您需要$unwind
达到这一点。您必须$unwind
分别对每个阵列级别。
从技术上讲,数组仍然存在children
,但$sum
可用于“对值数组求和”以及“为分组键累加”。因此. $sum: { $sum
_$group
回报:
{ "_id" : "Manhattan", "count" : 5 }
根据问题中提供的详细信息。
推荐阅读
- javascript - 如果刷新令牌已使用 axios 过期,则正确重定向用户
- javascript - 收到以下错误“失败:未知错误:a.tagName.toUpperCase 不是函数”
- r - 如何以编程方式评估空 quosure?
- json - Gtmetrix 使用本机反应获取报告
- angular - Angular - 如何将角度变量绑定到 html 并显示
- android - 如何让 Firebase 在数据库的三个不同区域显示相同的 ID?
- javascript - TypeError: undefined is not an object (evaluating 'store.getState')
- image-processing - 缝合在静止相机的视野中部分可见的移动物体
- python - pyspark 数据帧的慢速过滤
- javascript - 如何使用 selectize.js 设置选择的默认选项