首页 > 解决方案 > 子文档中不同的 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 中处理查询的新手,所以我非常感谢任何帮助。谢谢。

标签: node.jsmongodbmongooseaggregation-framework

解决方案


你有点接近,只是一些变化:

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 }

根据问题中提供的详细信息。


推荐阅读