node.js - MongoDB 查询子文档中的不同内容

标签 node.js mongodb mongoose aggregation-framework

我正在使用 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/

相关文章:

javascript - 通过 Ruby 将 HTML 表单发送到 MongoDB

javascript - Mongoose .js : force always populate

node.js - Mongoose:查找、更新、保存 - 没有错误,保存回调也发生变化,但在 MongoDB 中没有

javascript - 根据 React.Js 中第一个下拉列表中的选择填充第二个下拉列表

mongodb - 如何为 mongodb 设置永久 dbpath

java - 如何在Java Mongodb投影操作中给出$ObjectId

mongodb - 如何在 typescript 中输入 Mongoose ObjectID数组

node.js - 不同 promise 失败期间的不同重定向会导致错误 : cannot call http. ServerResponse.end()

node.js - Node Web 服务器外部不可见,但 Python 可见(MacOS)

javascript - 浏览器和服务器 JavaScript 中的十六进制字符串输出不同