如何构建具有嵌套和/或条件的mongo聚合管道



我正在尝试构建一个聚合管道,该管道使用AND(OR(AND)条件过滤掉文档。

我需要的是类似的东西

if (A == "A" && B == "B" && (C == NULL || (C != NULL && C == "C")))

我的查询如下所示。

内部:

var x = new BsonDocument
{
{
"$or",
new BsonArray
{
new BsonDocument {{"C", BsonNull.Value}},
new BsonDocument
{
{
"$and",
new BsonArray
{
new BsonDocument
{
{
"C",
new BsonDocument {{"$ne", BsonNull.Value}}
}
},
new BsonDocument {{"C", C}}
}
}
}
}
}
};

则全过滤器为

var filter = new BsonDocument
{
{
"$and",
new BsonArray
{
new BsonDocument {{"A", A}},
new BsonDocument {{"B", B}},
x
}
}
};

然后我这样称呼它:

var y = await collection.Aggregate().Match(filter).ToListAsync();

然而,它没有返回任何结果,尽管它应该返回。

在我的调试器中,最后的Bson看起来像:

{
{
"$and": [
{
"A": "A"
},
{
"B": "B"
},
{
"$or": [
{
"C": null
},
{
"$and": [
{
"C": {
"$ne": null
}
},
{
"C": "C"
}
]
}
]
}
]
}
}

设法弄清楚了。我更改了查询以将其构建为匹配,因为使用mongo-shell:测试更容易

var match = new BsonDocument
{
{
"$match",
new BsonDocument
{
{
"$and",
new BsonArray
{
new BsonDocument {{"A", A}},
new BsonDocument {{"B", B}},
new BsonDocument
{
{
"$or",
new BsonArray
{
new BsonDocument {{C, BsonNull.Value}},
new BsonDocument
{
{
"$and",
new BsonArray
{
new BsonDocument
{
{
"C",
new BsonDocument {{"$ne", BsonNull.Value}}
}
},
new BsonDocument {{"C", C}}
}
}
}
}
}
}
}
}
}
}
};

希望这能帮助任何遇到类似查询问题的人。

最新更新