$ lookup数组mongo聚合中的每个元素

时间:2018-08-27 15:28:33

标签: mongodb mongoose aggregation

我有一个用户架构,其中的人员字段包含viewers属性,该属性包含一个ObjectId数组,例如作为用户集合本身的引用

{
    "username": "user1",
    "password": "password",
    "email": "user1@gmail.com",
    "people": [{
            "id": 1,
            "viewers": ["ObjectId....", "ObjectId...."]
        },
        {
            "id": 2,
            "viewers": ["ObjectId....", "ObjectId...."]
        }
    ]
}

我需要对查看器中的每个元素进行$lookup操作,问题是当我在管道下面使用时,为每个文档推送相同的查看器

{
  $unwind: {
    path: "$people.viewers",
    preserveNullAndEmptyArrays: true
  }
},
{
  $lookup: {
    from: "users",
    localField: "people.viewers",
    foreignField: "_id",
    as: "people"
  }
},
{
  $unwind: {
    path: "$viewers",
    preserveNullAndEmptyArrays: true
  }
},
{
  $project: {
    username: 1,        
    "viewers.username": 1    
  }
},
{
  $group: {
    _id: "$_id",
    username: { $first: "$username" },    
    people: { $first: "$people" },
    viewers: { $push: "$viewers" }
  }
},
{
  $project: {
    username: 1,    
    "people.id": 1,
    "people.viewers": "$viewers"
  }
}

该聚合有什么问题

1 个答案:

答案 0 :(得分:1)

您可以在mongodb 3.4 及更高版本

中尝试以下聚合
User.aggregate([
  { "$unwind": { "path": "$people", "preserveNullAndEmptyArrays": true }},
  { "$lookup": {
    "from": "users",
    "localField": "people.viewers",
    "foreignField": "_id",
    "as": "people.viewers"
  }},
  { "$group": {
    "_id": "$_id",
    "username": { "$first": "$username" },    
    "email": { "$first": "$email" },
    "people": { "$push": "$people" }
  }}
])