json下面代表我的集合的文档结构。
{
"_id" : ObjectId("591a653c366df19100ed0fbc"),
"sno" : 1,
"chapterName" : "chapter 1: Express JS",
"overView" : "Overview of Express JS",
"sections" : [
{
"title" : "The Node.js philosophy",
"subSections" : [
{
"sno" : 1,
"title" : "Small core 1",
"content" : "The Node.js core itself has its foundations 1"
},
{
"sno" : 2,
"title" : "Small core 2",
"content" : "The Node.js core itself has its foundations 2"
}
]
},
{
"title" : "The Node.js philosophy 2",
"subSections" : [
{
"sno" : 1,
"title" : "Small core 1",
"content" : "The Node.js core itself has its foundations 1"
},
{
"sno" : 2,
"title" : "Small core 2",
"content" : "The Node.js core itself has its foundations 2"
}
]
}
]
}
我想写一个查询,它将以下面提到的方式返回所有记录的数据(不包括"内容")
{
"_id" : ObjectId("591a653c366df19100ed0fbc"),
"sno" : 1,
"chapterName" : "chapter 1: Express JS",
"overView" : "Overview of Express JS",
"sections" : [
{
"title" : "The Node.js philosophy",
"subSections" : [
{
"sno" : 1,
"title" : "Small core 1"
},
{
"sno" : 2,
"title" : "Small core 2"
}
]
},
{
"title" : "The Node.js philosophy 2",
"subSections" : [
{
"sno" : 1,
"title" : "Small core 1"
},
{
"sno" : 2,
"title" : "Small core 2"
}
]
}
]
}
知道如何实现这个目标吗?
答案 0 :(得分:0)
可行,但“不是微不足道的”。这需要大量使用$map
和.aggregate()
db.collection.aggregate([
{ "$project": {
"sno": 1,
"chapterName": 1,
"overView": 1,
"sections": {
"$map": {
"input": "$sections",
"as": "section",
"in": {
"title": "$$section.title",
"subSections": {
"$map": {
"input": "$$section.subSections",
"as": "subSection",
"in": {
"sno": "$$subSection.sno",
"title": "$$subSection.title"
}
}
}
}
}
}
}}
])
我只是想提一下“扁平化”,除了考虑为什么不使用嵌套数组的所有其他考虑之外,只需考虑这些数据:
{
"_id" : ObjectId("5921745d13fbc408ee20a60a"),
"a" : 1,
"b" : [
{ "a" : 1, "b" : 2, "c" : 3 },
{ "a" : 4, "b" : 5, "c" : 6 }
]
}
由于这只是一个深度的数组级别,如果我想要排除"c"
属性,那么我需要做的就是:
db.collection.find({},{ "b.c": 0 })
我当然得到了:
{
"_id" : ObjectId("5921745d13fbc408ee20a60a"),
"a" : 1,
"b" : [
{ "a" : 1, "b" : 2 },
{ "a" : 4, "b" : 5 }
]
}
这显然比在聚合投影中嵌套$map
语句简单得多。
深思熟虑。