gpt4 book ai didi

node.js - 查找后在对象数组中设置字段。蒙古数据库

转载 作者:行者123 更新时间:2023-12-02 18:28:13 26 4
gpt4 key购买 nike

我有两个集合usersposts

用户有这样的文档:

{
_id: ObjectId('611142303c409b5dc826e563'),
name: 'foo'
}

posts 包含如下文档:

{
_id: ObjectId('611142303c409b5dc826e111'),
comments:[
{
owner: ObjectId('611142303c409b5dc826e563'),
description: "my description"
},
{
owner: ObjectId('611142303c409b5dc826e333'),
description: "my description2"
}
]
}

当我收到服务器端请求时,我需要返回所有者的整个文档,而不仅仅是其 ID。

例如,对于我必须返回的 get 请求:

{
_id: ObjectId('611142303c409b5dc826e111'),
comments:[
{
owner:{
_id: ObjectId('611142303c409b5dc826e563'),
name: 'foo'
},
description: "my description"
},
{
owner: {
_id: ObjectId('611142303c409b5dc826e555'),
name: 'foo2'
},
description: "my description2"
}
]
}

为此,我执行了以下管道:

[
$lookup:{
from: 'owners',
localField: 'comments.owner',
foreignField: '_id',
as: 'owners_comments'
}
]

通过这种方式,我得到了一组在一个特定文档中有评论的所有者。

我的问题是如何为每条评论获取正确的所有者个人资料?我知道我可以更轻松地在服务器端进行操作,但我更喜欢在数据库端进行。

我想映射每个评论并在owners_comments内部进行过滤,但在 mongo 聚合中我遇到了一些问题。

你有什么建议吗?

最佳答案

您必须$unwind注释数组,然后执行$lookup,然后您想要$group恢复原始结构,如下所示:

db.posts.aggregate([
{
$unwind: "$comments"
},
{
$lookup: {
from: "owners",
localField: "comments.owner",
foreignField: "_id",
as: "owners"
}
},
{
$group: {
_id: "$_id",
comments: {
$push: {
owner: "$comments.owner",
description: "$comments.description",
owner_profile: {
"$arrayElemAt": [
"$owners",
0
]
},

}
}
}
}
])

Mongo Playground

关于node.js - 查找后在对象数组中设置字段。蒙古数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69810826/

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