mongodb - $match 中的 Mongo 聚合条件查询
问题描述
基本上,如果存在一个字段,我想运行一个查询,否则,我想运行一个单独的。
`db.Collection.aggregate([
{
$match: {
$cond: [{if fieldOnCollection:{$exists:true}}, {fieldOnCollection:'foo'}, {anotherField:'bar'}]
}
}
]);`
我只见过$cond
在其他阶段使用过,而不是构建由集合本身的字段组成的查询的实际部分
解决方案
Query1
(没有聚合运算符)
db.collection.aggregate({
"$match": {
"$or": [
{
"fieldOnCollection": "foo"
},
{
"$and": [
{
"fieldOnCollection": {
"$exists": false
}
},
{
"anotherField": "bar"
}
]
}
]
}
})
Query2
(与您的查询类似的聚合运算符)
- 如果字段存在,测试它是否与“foo”相等
- 否则检查其他字段是否等于“bar”
db.collection.aggregate([
{
"$match": {
"$expr": {
"$cond": [
{
"$ne": [
{
"$type": "$fieldOnCollection"
},
"missing"
]
},
{
"$eq": [
"$fieldOnCollection",
"foo"
]
},
{
"$eq": [
"$anotherField",
"bar"
]
}
]
}
}
}
])
推荐阅读
- java - 如何在 Spring Boot 中完全禁用 Hibernate 异常
- kernel - fedora 27 内核崩溃 4.16.7-200.fc27.x86_64
- python - 在 django 中创建自定义命令
- windows - 尝试从指定用户的网络驱动器复制数据但出现错误
- r - Replacing string with greater/smaller than symbol is not replaced
- arrays - 在 Swift 4 中改组多项选择数组
- html - 如何将两个或三个元素连续放置?
- php - `<<<_HTML_` 在 php 中有什么作用?
- javascript - 如何从服务器连续发送数据到浏览器
- jquery - 带有 jquery 的下拉菜单