[英]MongoDB query distinct in subdocuments
I'm using Mongoose with NodeJS (typescript).我正在将 Mongoose 与 NodeJS(打字稿)一起使用。 I'm trying to sum the count per location.我正在尝试对每个位置的计数求和。 Example output :示例输出:
[
{ 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
}
]
}
]
}
},
{
....
}
]
The last query that I build was :我构建的最后一个查询是:
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));
});
But I'm new handle queries in MongoDB with Mongoose, so any help I really appreciate.但是我是使用 Mongoose 在 MongoDB 中处理查询的新人,所以我非常感谢任何帮助。 thanks.谢谢。
You were kind of close, just a few changes:你有点接近,只是一些变化:
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
})
So since you have arrays inside an array and you want to get down to the "name"
property inside the "locations"
you need to $unwind
to that point.因此,由于您在数组中有数组,并且想要深入了解"locations"
内的"locations"
"name"
属性,因此您需要$unwind
到该点。 You must $unwind
each array level separately.您必须分别$unwind
每个数组级别。
Technically there is still the children
array as well, but $sum
can be used to "sum an array of values" as well as "accumulate for a grouping key" .从技术上讲,还有children
数组,但$sum
可用于“对一组值求和”以及“为分组键累加” 。 Hence the $sum: { $sum
statement within the $group
.因此$sum: { $sum
$group
$sum: { $sum
语句。
Returns:返回:
{ "_id" : "Manhattan", "count" : 5 }
From the detail supplied in the question.从问题中提供的细节来看。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.