c# - 如何使用嵌套和/或条件构建 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}}
}
}
}
}
}
}
}
}
}
}
};
希望这可以帮助任何遇到类似查询问题的人。
推荐阅读
- sql - 从存储过程插入返回记录 - SQL
- c# - Serilog 与 .net c# 类库的集成
- google-app-engine - 无法在 Google Cloud 上创建实例 - “区域...”没有足够的资源
- firebase - Firebase Web SDK createUserWithEmailAndPassword 在创建后未登录用户
- html - Slider 中的内容不适合移动设备
- html - 制作标题的完美方法
- python-3.x - 如何在终端中使用 python 3.7.1 从我的桌面打开文本文件
- android - Sms Messages not Loading into ListView
- javascript - Access HTML input array field via javascript
- javascript - 使用 WebRTC 进行对等连接时出现信号错误