[英]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.