我有一个示例文档,我正试图在MongoDB聚合管道中投影它。我用一个大致如下的文档进行测试:
{
"_id" : "",
"title" : "Questions",
"sortIndex" : 0,
"topics" : [
{
"_id" : "",
"title" : "Creating a Question",
"sortIndex" : 1,
"thumbnail" : "CreatingAQuestion.jpg",
"seenBy" : [ "user101", "user202" ],
"pages" : [
{
"visual" : "SelectPlanets.gif",
"text" : "Some Markdown"
}
]
},
{
"_id" : "",
"title" : "Deleting a Question",
"sortIndex" : 0,
"thumbnail" : "DeletingAQuestion.jpg",
"seenBy" : [ "user101" ],
"pages" : [
{
"visual" : "SelectCard.gif",
"text" : "Some Markdown"
}
]
}
]
}
我试图获得的结果大致如下:
{
"_id" : "",
"title" : "Questions",
"topics" : [
{
"title" : "Creating a Question",
"thumbnail" : "CreatingAQuestion.jpg",
"seen" : true
},
{
"title" : "Deleting a Question",
"thumbnail" : "DeletingAQuestion.jpg",
"seen" : false
}
]
}
具体来说,我正在努力解决的问题是
seen
旗帜
docs
在嵌入文档中投影或添加/重置字段时。。。
... 或者可以嵌套字段:
contact: { address: { country: <1 or 0 or expression> } }
表示
嵌套字段时,不能在嵌入的文档中使用点符号来指定字段,例如,联系人:
{ "address.country": <1 or 0 or expression> }
所以我试图找出如何在表达式中“引用”子文档字段。那句话表明我不能使用
点符号
但当我似乎也无法使用嵌套符号时。以下是我目前掌握的信息:
db
.getCollection('chapters')
.aggregate([
{
$project: {
title: 1,
topics: {
title: 1,
thumbnail: 1,
publishedAt: 1,
test: "$seenBy",
seen: { $in: ["user202", "$seenBy"] },
}
}
}
])
user202
到我现在的查询,并期待看到
和
假
对于2个文档。我还加入了一个
test
字段以绘制
seenBy
{
"_id" : "",
"title" : "Questions",
"topics" : [
{
"title" : "Creating a Question",
"thumbnail" : "CreatingAQuestion.jpg",
"test" : [
"user101",
"user202"
],
"seen" : true
},
{
"title" : "Deleting a Question",
"thumbnail" : "DeletingAQuestion.jpg",
"test" : [
"user101",
"user202"
],
"seen" : true
}
]
}
很明显,我的“$seenBy”没有访问正确的主题,因为
测验
所以最终我的问题是,我如何访问
seenBy公司
子文档以便创建表达式?
我用多个
$project
和一个
$unwind
但是想试着压缩/清理一下。