gpt4 book ai didi

mongodb - "populate"具有 $lookup 的字段而不覆盖现有值

转载 作者:行者123 更新时间:2023-12-03 02:50:43 25 4
gpt4 key购买 nike

考虑以下文档:

A 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"
]
}

A users文档

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

mongo shell 中,我尝试检索 communicationsmessages.authorId “填充”为 userInfo我的领域user文档。

我尝试用 $lookup 来做到这一点像这样:

db.communications.aggregate([
{
$lookup:
{
from: "users",
localField: "messages.authorId",
foreignField: "_id",
as: "messages.authorId"
}
}
])

但是场messages.authorId被覆盖。

我如何“填充”我的 userInfo字段而不替换现有值?

感谢您的帮助。

最佳答案

因为你的messages是一个数组字段,当您提供 .dot 时,它会用新对象覆盖现有数组。 as 中的符号 ( "messages.authorId" ) 表达式。

因此,如果您想填充 messages 内的每个用户您需要 $unwind 的数组messages首先添加一个新的数组,然后 $group 再次回滚到数组中。

db.communications.aggregate([
{ "$unwind": "$messages" },
{ "$lookup": {
"from": "users",
"localField": "messages.authorId",
"foreignField": "_id",
"as": "messages.authorId"
}},
{ "$unwind": "$messages.authorId" },
{ "$group": {
"_id": "$_id",
"messages": { "$push": "$messages" },
"type": { "$first": "$type" },
"title": { "$first": "$title" },
"receivers": { "$first": "$receivers" }
}}
])

关于mongodb - "populate"具有 $lookup 的字段而不覆盖现有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53618475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com