代码之家  ›  专栏  ›  技术社区  ›  Ashh

$嵌套数组ID的查找聚合

  •  0
  • Ashh  · 技术社区  · 7 年前

    我有 Label ,则, Conversations Messages 模型。。。

    标签包含对话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 
    }]
    

    现在我有了 messages 在…内 conversations

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

    那么,如何将$lookup应用于其中的messages字段呢

    标签->对话->messasges公司

    提前感谢

    1 回复  |  直到 6 年前
        1
  •  1
  •   Ashh    7 年前

    您必须使用 $unwind 在…上 $conversations 。这将导致 conversations 数组爆炸后,您手中的文档将与对话数量一样多。

    那么你应该 $lookup ,和(如果需要) $group 回到你以前的生活中 $展开

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