我正在使用mongo查询聚合,其中有这样的数据
[
{
"token" : "c1",
"class" : "bscs",
courses : ["ITM", "CS54", "KHE"]
}
]
我正在使用 $ unwind 来中断课程
[
{
"token" : "c1",
"class" : "bscs",
courses : "ITM"
},
{
"token" : "c1",
"class" : "bscs",
courses : "CS54"
},
{
"token" : "c1",
"class" : "bscs",
courses : "KHE"
}
]
我想要的是,它应该像:-
[
{
"token" : "c1",
"class" : "bscs",
courses : "ITM"
},
{
"token" : "",
"class" : "",
courses : "CS54"
},
{
"token" : "",
"class" : "",
courses : "KHE"
}
]
因为我有一个表结构,需要显示数据,这非常复杂,并且在那里显示了来自不同查询的许多数据,所以我无法更新它。如果它是这样,那么我可以在表中显示为
我的汇总是
[ {.....}, // others projections and matches
{
$unwind: {
path: '$courses'
}
}
]
答案 0 :(得分:0)
在运行$unwind时可以使用includeArrayIndex
选项,然后在索引不等于0
的情况下使用$cond设置空字符串
db.collection.aggregate([
{
$unwind: {
path: "$courses",
includeArrayIndex: "index"
}
},
{
$project: {
token: { $cond: [ { $eq: [ "$index", 0 ] }, "$token", "" ] },
class: { $cond: [ { $eq: [ "$index", 0 ] }, "$class", "" ] },
courses: 1
}
}
])