【问题标题】:$lookup aggregation for nested array ids嵌套数组 id 的 $lookup 聚合
【发布时间】:2018-06-05 02:16:23
【问题描述】:

我有LabelConversationsMessages 模型...

标签包含对话 id...我使用了 $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 
}]

现在我在conversations 里面有messages

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

那么我如何为里面的消息字段应用 $lookup

标签 -> 对话 -> 消息

提前致谢

【问题讨论】:

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


    【解决方案1】:

    您必须在$conversations 上使用$unwind。这将导致您的 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'
            }
        }
    ])
    

    【讨论】:

    • 嗨@Webvoid ...以上答案对我有用...但对话正在分裂...我如何申请$group
    猜你喜欢
    • 2021-08-04
    • 2021-08-09
    • 1970-01-01
    • 2020-04-03
    • 2020-09-01
    • 2017-07-26
    • 2020-07-30
    • 1970-01-01
    • 2020-12-31
    相关资源
    最近更新 更多