$ group和$ lookup

时间:2018-06-30 07:53:10

标签: mongodb mongodb-query aggregation-framework

我在MongoDB查询中有一个问题。 我有以下用户集合:

{
    "_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
    }
]

感谢助手:)

2 个答案:

答案 0 :(得分:2)

如果您拥有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
  }}
])

如果您想按兴趣分组name

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
  }}
])

答案 1 :(得分:0)

 db.collection.aggregate(
  {
    $group: {
      _id: '$interests'
    }
  },
  {
    $group: {
      _id: '$name',
      count: {
        $sum: 1
      }
    }
  }
)