使用$ lookup“填充”字段,而不会覆盖现有值

时间:2018-12-04 17:29:37

标签: mongodb mongodb-query aggregation-framework

请考虑以下文件:

communications文档

{
    "_id" : ObjectId("5c069a6acbd69e0f61983850"),
    "type" : "request",
    "title" : "test 1",
    "messages" : [ 
        {
            "authorId" : "7b0dcd22-c3bb-426f-8235-671b82acee98",
            "body" : "test 1",
            "createdAt" : ISODate("2018-12-04T15:16:58.342Z")
        }
    ],
    "receivers" : [ 
        "e75f3849-09bb-46a4-a05d-885b6d31ccc3"
    ]
}

users文档

{
    "_id" : "7b0dcd22-c3bb-426f-8235-671b82acee98",
    "userInfo" : {
        "avatarKey" : "7b0dcd22-c3bb-426f-8235-671b82acee98/avatars/Dandelion.png",
        "familyName" : "Doe",
        "givenName" : "John"
    }
}

mongo shell 中,我尝试使用communications的{​​{1}}字段中的messages.authorId“填充”来检索userInfo文档。

我试图用user来做到这一点:

$lookup

但是字段db.communications.aggregate([ { $lookup: { from: "users", localField: "messages.authorId", foreignField: "_id", as: "messages.authorId" } } ]) 被覆盖。

如何在不替换现有值的情况下“填充”我的messages.authorId字段?

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

由于您的messages是一个数组字段,因此当您在 .dot 中提供as表示法时,它将用新对象覆盖现有数组({{ 1}})表达式。

因此,如果您要填充数组"messages.authorId"中的每个用户,则需要先$unwind messages数组以添加新密钥,然后$group来回滚再次进入数组。

messages
相关问题