node.js - 查找后在对象数组中设置字段。蒙古数据库
问题描述
我有两个系列users
和posts
.
用户有这样的文件:
{
_id: ObjectId('611142303c409b5dc826e563'),
name: 'foo'
}
帖子有这样的文件:
{
_id: ObjectId('611142303c409b5dc826e111'),
comments:[
{
owner: ObjectId('611142303c409b5dc826e563'),
description: "my description"
},
{
owner: ObjectId('611142303c409b5dc826e333'),
description: "my description2"
}
]
}
当我收到请求服务器端时,我需要返回所有者的整个文档,而不仅仅是它的 ID。
例如,对于我必须返回的获取请求:
{
_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
comments 数组,然后执行$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
]
},
}
}
}
}
])
推荐阅读
- artificial-intelligence - 我的 CLIPS 代码有什么不好的 - 或/和变化或 else-if 语法?
- r - case_when 在 mutate 函数中出错:输入必须是向量
- python - 在python中将所有零移动到数组的末尾
- javascript - 删除 Firebase 中除个人数据外的先前字段
- r - 如何将 Dataframe 作为 R 中的列表放入一个单元格中
- postman - 邮递员 - 基于迭代计数忽略来自跑步者的请求
- python - 多少步和大 O 复杂度
- clickhouse - ORDER BY WITH FILL 空结果
- keras - 无法通过减少层数、增加Dropout或增加学习率来防止CNN模型过拟合
- java - Typescript 中的 Java 枚举等价物