[英]Count how many documents are in a collection per value for a specific field - MongoDB
[英]How to group documents of a collection to a map with unique field values as key and count of documents as mapped value in mongodb?
我需要一個 mongodb 查詢來獲取具有唯一值field(f)作為集合中的鍵的值的列表或映射,以及在 field(f) 中與映射值具有相同值的文檔計數。 我怎樣才能做到這一點?
例子:
Document1: {"id":"1","name":"n1","city":"c1"}
Document2: {"id":"2","name":"n2","city":"c2"}
Document3: {"id":"3","name":"n1","city":"c3"}
Document4: {"id":"4","name":"n1","city":"c5"}
Document5: {"id":"5","name":"n2","city":"c2"}
Document6: {"id":"6,""name":"n1","city":"c8"}
Document7: {"id":"7","name":"n3","city":"c9"}
Document8: {"id":"8","name":"n2","city":"c6"}
如果 group by 字段是“name”,查詢結果應該是這樣的:
{"n1":"4",
"n2":"3",
"n3":"1"}
如果列表也按降序排序,那就太好了。
值得注意的是,使用數據點作為字段名稱(鍵)在某種程度上被認為是一種反模式,並使工具變得困難。 盡管如此,如果您堅持將數據點作為字段名稱,您可以使用這種復雜的聚合來執行您想要的查詢輸出......
聚合
db.collection.aggregate([
{
$group: { _id: "$name", "count": { "$sum": 1} }
},
{
$sort: { "count": -1 }
},
{
$group: { _id: null, "values": { "$push": { "name": "$_id", "count": "$count" } } }
},
{
$project:
{
_id: 0,
results:
{
$arrayToObject:
{
$map:
{
input: "$values",
as: "pair",
in: ["$$pair.name", "$$pair.count"]
}
}
}
}
},
{
$replaceRoot: { newRoot: "$results" }
}
])
聚合說明
這是一個 5 階段聚合,包括以下內容...
樣本結果
{ "n1" : 4, "n2" : 3, "n3" : 1 }
無論出於何種原因,您將計數顯示為字符串所需的結果,但我的結果將計數顯示為整數。 我認為這不是問題,實際上可能是首選。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.