Mongodb $groupwith$lookup
我在MongoDB查询中有一个问题。 我拥有以下用户集合:Mongodb $groupwith$lookup,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,我在MongoDB查询中有一个问题。 我拥有以下用户集合: { "_id" : ObjectId("5aa03bf97d6e1d28a020f488"), "name":"A1", "interests" : [ ObjectId("5aa03b877d6e1d28a020f484"), ObjectId("5aa03bb47d6e1d28a020f485") ] }, { "_id" : ObjectId("5aff
{
"_id" : ObjectId("5aa03bf97d6e1d28a020f488"),
"name":"A1",
"interests" : [
ObjectId("5aa03b877d6e1d28a020f484"),
ObjectId("5aa03bb47d6e1d28a020f485")
]
},
{
"_id" : ObjectId("5affd69339f67335303ddf77"),
"name":"A2",
"interests" : [
ObjectId("5aa03b877d6e1d28a020f484")
]
},
{
"_id" : ObjectId("5affd69339f673ddfjfhri45"),
"name":"A3",
"interests" : [
ObjectId("5aa03bb47d6e1d28a020f485"),
]
},
{
"_id" : ObjectId("5affd69339f67365656ddfg4f"),
"name":"A4",
"interests" : [
ObjectId("5aa16eb8890cbb4c582e8a38"),
]
}
“兴趣”集合将显示以下示例:
{
"_id" : ObjectId("5aa16eb8890cbb4c582e8a38"),
"name" : "Swimming",
},
{
"_id" : ObjectId("5aa03bb47d6e1d28a020f485"),
"name" : "Basketball",
},
{
"_id" : ObjectId("5aa03b877d6e1d28a020f484"),
"name" : "Fishing",
}
我想写一个查询,计算所有用户的兴趣类型:
预期结果如下:
[
{
"name":"fishing"
"count":21
},
{
"name":"Basketball"
"count":15
}
]
感谢您的帮助:)如果您有mongodb 3.6,那么您可以在下面尝试
db.collection.aggregate([
{ "$lookup": {
"from": Intrest.collection.name,
"let": { "interests": "$interests" },
"pipeline": [
{ "$match": {
"$expr": { "$in": [ "$_id", "$$interests" ] },
"name": "Swimming",
}}
],
"as": "interests"
}},
{ "$unwind": "$interests" },
{ "$group": {
"_id": "$interests.name",
"count": { "$sum": 1 }
}},
{ "$project": {
"name": "$_id", "count": 1
}}
])
如果你想与兴趣小组姓名
db.collection.aggregate([
{ "$lookup": {
"from": Intrest.collection.name,
"let": { "interests": "$interests" },
"pipeline": [
{ "$match": { "$expr": { "$in": [ "$_id", "$$interests" ] } }}
],
"as": "interests"
}},
{ "$unwind": "$interests" },
{ "$group": {
"_id": "$interests.name",
"count": { "$sum": 1 }
}},
{ "$project": {
"name": "$_id", "count": 1
}}
])
嗨,名称应该是兴趣的名称,例如,有4个用户对“游泳”感兴趣嗨,我添加了兴趣收集示例结果是列表用户,但使用兴趣名称而不是ID,这不是目的。预期的结果是在其应用程序中具有“swiiming”的用户的计数/总数interest@RanAlcobi请检查更新的两个答案。。。这肯定会奏效的。安东尼,游泳是唯一的例子。结果应该是“对于每个兴趣->获取兴趣数组中的用户数量(计数)”仍然下面的答案不适用于您?
db.collection.aggregate(
{
$group: {
_id: '$interests'
}
},
{
$group: {
_id: '$name',
count: {
$sum: 1
}
}
}
)