【问题标题】:Get distinct list of ids from another collection where array field contains id from item in current collection in MongoDB从另一个集合中获取不同的 id 列表,其中数组字段包含 MongoDB 中当前集合中项目的 id
【发布时间】:2021-09-03 01:14:57
【问题描述】:

我在 MongoDB 数据库中有多个集合:

users: [{
  id: "name1",
  groups: ["group1"]
}, {
  id: "name2",
  groups: ["group2"]
}]

groups: [{
  id: "group1",
  name: "first group"
}, {
  id: "group2",
  name: "second group"
}, {
  id: "group3",
  name: "third group"
}]

我想从groups 集合中获取所有记录,但还想在响应中的每条记录中添加一个assignedTo 字段,其中包含属于该组的用户ID 列表:

[{
  id: "group1",
  name: "first group",
  assignedTo: ["user1"]
}, {
  id: "group2",
  name: "second group"
  assignedTo: ["user2"]
}, {
  id: "group3",
  name: "third group"
  assignedTo: []
}]

如何使用聚合框架来做到这一点?谢谢

附:一个组可能没有分配用户,但它仍然需要在响应中显示为

[
...
{
  id: "group3",
  name: "third group",
  assignedTo: [] # empty array
}]

【问题讨论】:

  • users 是用户的集合,还是用户项是数组?
  • Users 是一个单独的集合以及组,每个用户都有一个其所属组的列表

标签: mongodb aggregation-framework


【解决方案1】:

$lookup给用户添加组数据

$unwind破坏组数组

$group按组创建数组

$project 根据需要确定数据

db.collection('users').aggregate(
[
  {
    '$lookup': {
      'from': 'groups', 
      'localField': 'groups', 
      'foreignField': '_id', 
      'as': 'groups'
    }
  }, {
    '$unwind': {
      'path': '$groups'
    }
  }, {
    '$group': {
      '_id': {
        'id': '$groups._id', 
        'name': '$groups.name'
      }, 
      'assignedTo': {
        '$addToSet': '$$ROOT._id'
      }
    }
  }, {
    '$project': {
      'id': '$_id.id', 
      'name': '$_id.name', 
      'assignedTo': 1, 
      '_id': 0
    }
  }
]
)

【讨论】:

  • 我假设如果一个组没有分配任何用户,它就不会显示,对吧?我已经更新了问题
  • 我们从用户集合中填充组,因此不可能有没有assignedTo的文档
猜你喜欢
  • 2016-05-16
  • 1970-01-01
  • 2016-11-19
  • 2012-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多