MongoDB聚合:$unwind
$unwind
是MongoDB的聚合管道中的一个操作符,它用于将文档中的数组字段拆分成多个文档。如果数组字段中有null值或空数组,可以选择是否生成文档,也可以指定保留数组中的哪些值或排除哪些值。
以下是一个使用$unwind
的例子:
假设我们有一个集合students
,其中的文档包含一个subjects
数组字段,我们想要将每个学生的每个科目单独展示出来。
db.students.aggregate([
{
$unwind: "$subjects"
}
]);
如果我们想要过滤掉科目为空的情况,可以这样写:
db.students.aggregate([
{
$unwind: {
path: "$subjects",
preserveNullAndEmptyArrays: false // 不保留空值
}
}
]);
如果我们只对特定的科目感兴趣,可以使用includeArrayIndex
或filter
来筛选:
db.students.aggregate([
{
$unwind: {
path: "$subjects",
includeArrayIndex: "scoreIndex",
preserveNullAndEmptyArrays: true,
filter: { score: { $gt: 60 } } // 只保留分数大于60的科目
}
}
]);
在这个例子中,includeArrayIndex
会在新文档中添加一个字段scoreIndex
,包含原数组中元素的索引。filter
则用于指定筛选条件,只有满足条件的数组元素会被展开。
评论已关闭