概括
这个方法一般与 $cond
一起使用,如果匹配成功,则执行 $$DESCEND
或 $$PRUNE
或 $$KEEP
指令。
下面的指令意思就是:递级匹配,匹配的话,当前级别的所有字段都会返回,然后匹配下一级,直到某一级的 tags
这个 array
里木有 "G"
的时候,停止匹配,且该级别的所有字段都不会返回。
如果有更好的理解方式,可以在文章下面留言。
db.test.aggregate([
{$match: {year:2014}},
{$redact:
{$cond:
{
if: {$gt: [{$size: {$setIntersection: ["$tags", ["G"]]}}, 0]},
then: "$$DESCEND",
else: "$$PRUNE"
}
}
}
]).pretty()
DESCEND、PRUNE、KEEP 这三者有什么区别呢?
{
"_id" : 1,
"title" : "123 Department Report",
"tags" : [
"G",
"STLW"
],
"year" : 2014,
"subsections" : [
{
"subtitle" : "Section 1: Overview",
"tags" : [
"SI",
"G"
],
"content" : "Section 1: This is the content of section 1."
},
{
"subtitle" : "Section 2: Analysis",
"tags" : [
"STLW"
],
"content" : "Section 2: This is the content of section 2."
},
{
"subtitle" : "Section 3: Budgeting",
"tags" : [
"TK"
],
"content" : {
"text" : "Section 3: This is the content of section3.",
"tags" : [
"HCS"
]
}
}
]
}
- $$DESCEND
递增匹配,匹配就返回当前级别的所有字段,并继续匹配下一级别。 - $$PRUNE
当前级别如果不匹配的话,这个级别的所有字段都不会返回,且不会继续匹配下一级别。 - $$KEEP
当前级别如果匹配的话,这个级别的所有字段都会返回,且不会继续匹配下一级别。
网友评论