嵌套数组id的$ lookup聚合

时间:2018-03-30 10:17:55

标签: node.js mongodb mongoose mongodb-query aggregation-framework

我有LabelConversationsMessages型号......

标签包含对话ID' s我使用了$ lookup,用于对话

const conversation = await Label.aggregate([
    { $match: { _id: mongoose.Types.ObjectId("5abcb74bb59afe4310c60266") } },
    { $lookup: {
        from: 'conversations',
        localField: 'conversations',
        foreignField: '_id',
        as: "conversations"
      }
    }])

并输出

之类的输出
[{ 
    _id: 5abcb74bb59afe4310c60266,
    name: 'Archive',
    value: 'archive',
    user: 5abc93a85d3914318cc8d3d7,
    conversations: [ [Object], [Object] ],
    __v: 0 
}]

现在我messages内有conversations

[{ 
    _id: 5abe07717a978c41b270b1bc,
    messages: [ 5abe07717a978c41b270b1bd ],
    members: [ 5abc93a85d3914318cc8d3d7, 5abc9467b7c99332f0a6813c ],
    __v: 0
}]

那么如何对

中的消息字段应用$ lookup

标签 - >对话 - > messasges

提前致谢

1 个答案:

答案 0 :(得分:1)

您必须在$unwind上使用$conversations。这会导致您的conversations数组爆炸,现在您手中的对话文件数量会很多。

然后你应该执行$lookup和(如果需要的话)$group来回溯$unwind之前的内容

const conversation = await Label.aggregate([
    { $match: { _id: mongoose.Types.ObjectId("5abcb74bb59afe4310c60266") } },
    { $lookup: {
        from: 'conversations',
        localField: 'conversations',
        foreignField: '_id',
        as: "conversations"
        }
    },
    { $unwind: "$conversations" },
    {
        $lookup: {
        from: 'messages', 
        localField: 'conversations.messages',
        foreignField: '_id',
        as: 'myMessages'
        }
    }
])