mongodb - 如何对嵌套数组中的属性值执行 $lookup?
问题描述
我有一个articles
包含一个数组的集合,comments
这个数组包含一个数组sub_comments
。这是它的样子:
let articleSchema = mongoose.Schema({
title: {type: String},
comments: [{
comment: {type: String},
creator: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
sub_comments: [{
comment: {type: String},
creator: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
}]
}]
});
我正在尝试运行一个对and字段执行 a 的aggregate
查询。这是我到目前为止尝试过的,但它不起作用:$lookup
comments.creator
sub_comments.creator
this.model('Article')
.aggregate([
{
$match: {_id: article_id}
},
{
$lookup: {
from: "users",
localField: "comments.creator",
foreignField: "_id",
as: "comments.creator"
}
},
{
$unwind: {
path: "$comments.creator",
preserveNullAndEmptyArrays: true
}
},
{
$lookup: {
from: "users",
localField: "comments.sub_comments.creator",
foreignField: "_id",
as: "comments.sub_comments.creator"
}
},
{
$unwind: {
path: "$comments.sub_comments.creator",
preserveNullAndEmptyArrays: true
}
},
{
$project: {
_id: 1,
title: 1,
"comments.comment": 1,
"comments.creator._id": 1,
"comments.creator.name": 1,
"comments.sub_comments.comment": 1,
"comments.sub_comments.creator._id": 1,
"comments.sub_comments.creator.name": 1
}
}
])
.exec(function (err, data) {
...
});
data
这是响应的示例:
[{
"_id": "5b7e1629d00a170018e11234",
"article": "My Article",
"comments": {
"comment": "This is the comment.",
"sub_comments": {},
"creator": {
"_id": "541g2dfeab1e470b00411234",
"name": "John Doe"
}
},
....
}]
注释应该是一个数组,而不是一个对象。这个特定的评论没有任何子评论,但显然,我也希望它能够工作。关于如何让它发挥作用的任何想法?
解决方案
带有查询的 as params
mongodb $lookup
会影响您的结果。
as 指定要添加到输入文档的新数组字段的名称。新的数组字段包含来自 from 集合的匹配文档。如果输入文档中已经存在指定的名称,则覆盖现有字段。
它将覆盖归档的 . 不添加它。如果您的外部是一个数组,它将使其成为对象并删除当前内容。
所以第二个 $lookup
总计不起作用。在您的查询中
如果你想保持当前的数据结构 intac 。你可以 as a new fieldname
和使用$project
来改变格式。
推荐阅读
- spring-boot - 如果我对 SpringBoot 项目使用 kill -9,它的异步线程会发生什么
- dpdk - 什么是RSS过滤功能?
- python - 在 Flask 中创建全文搜索
- arrays - MIPS 汇编语言数组
- reactjs - 如何将 buildId 设置为 config (publicRuntimeConfig) 或环境变量?
- c# - C# 正则表达式 - 排除文本开头和结尾的下划线和空格
- python - Plotly:如何突出显示某些 xticks?
- react-native - Expo遇到致命错误:错误:需要未知模块“./locale/en-us”
- windows - odbc dsn-less 连接字符串错误 IM002
- python - 通过命令行从 Snakemake 工作流的 python 可执行文件指定目标规则