繁体   English   中英

子文档中的MongoDB查询不同

[英]MongoDB query distinct in subdocuments

我正在将 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
})

因此,由于您在数组中有数组,并且想要深入了解"locations"内的"locations" "name"属性,因此您需要$unwind到该点。 您必须分别$unwind每个数组级别。

从技术上讲,还有children数组,但$sum可用于“对一组值求和”以及“为分组键累加” 因此$sum: { $sum $group $sum: { $sum语句。

返回:

{ "_id" : "Manhattan", "count" : 5 }

从问题中提供的细节来看。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM