Mongodb 按列表中的元素和字段计数
我有一个MongoDB集合,看起来像这样:Mongodb 按列表中的元素和字段计数,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我有一个MongoDB集合,看起来像这样: { "_id" : 1, "owner" : "Alice", airline: "RSAirlines", "content" : ["shoes", "pants", "sockets"]} { "_id" : 2, "owner" : "B
{ "_id" : 1, "owner" : "Alice", airline: "RSAirlines", "content" : ["shoes", "pants", "sockets"]}
{ "_id" : 2, "owner" : "Bob", airline: "RSAirlines", "content" : ["phone", "pants"]}
{ "_id" : 3, "owner" : "Charlie", airline: "RSAirlines", "content" : ["shoes", "pants", "bag"]}
{ "_id" : 4, "owner" : "Mary" ,airline: "AirES" "content" : ["sandals", "coins", "sockets"]}
{ "_id" : 5, "owner" : "Olivia", airline: "AirES", "content" : ["gloves", "pants", "sockets"]}
{ "_id" : 6, "owner" : "Dan", airline: "AirES", "content" : ["sockets", "wallet"]}
{ "_id" : 7, "owner" : "Erin", airline: "AirES", "content" : ["pants", "sockets", "dress"]}
我想对它们进行聚合
以获得以下结果:
{ "_id": "RSAirlines", "counts": {
"shoes": 2,
"pants": 3,
"sockets": 1,
"phone": 1,
"bag": 1
}}
{ "_id": "AirES", "counts": {
"sandals": 1,
"coins": 1,
"sockets": 4,
"wallet": 1,
"dress": 1,
"pants": 2
}}
以前我看到过计算元素的方法,但现在我想按航空公司
解构$unwind
数组内容
通过$group
航空公司和
内容获取总计数
由唯一的$组
和构造航空公司
数组键值格式计数
将键值数组转换为对象$arrayToObject
如果我想要每个内容的顶部
n
?你能举个例子吗,我没有得到确切的答案。就像前2个一样,它会输出:{id:“RSAirlines”,“counts:{“shoes”:2,“pants”:3,}{{id:“AirES”,“counts:{“sockets”:4,“pants”:2}{/code>看到了吗,您可以使用$sort by count和$slice来选择元素的数量。是的,这就是我要找的,谢谢
db.collection.aggregate([
{ $unwind: "$content" },
{
$group: {
_id: {
airline: "$airline",
content: "$content"
},
count: { $sum: 1 }
}
},
{
$group: {
_id: "$_id.airline",
counts: {
$push: {
k: "$_id.content",
v: "$count"
}
}
}
},
{ $project: { counts: { $arrayToObject: "$counts" } } }
])