Mongo查询以查找包含非null值的数组元素的文档,这些值都与指定值不匹配



我正试图找到一个mongo查询,它将查找所有包含数组的文档,其中没有任何元素具有某个值的属性。但是,如果所有元素都有空值或该属性缺少空值,则不应返回该文档。此外,不包含数组或数组为空的文档也应被忽略
即,只应返回该属性的某个非null值与该值不匹配的文档
例如,在以下示例中,我正在查找没有类型值为TYPE2myShoppingList元素的所有文档,因此以下文档将返回

{
"myShoppingList": [
{
"type": "TYPE1",
"someOtherAttribute" : "testValue1"
},
{
"type": null,
"someOtherAttribute" : "testValue2"
}
]
}

但以下文件不会被退回:

{
"myShoppingList": [
{
"type": "TYPE1",
"someOtherAttribute" : "testValue1"
},
{
"type": "TYPE2", // value 'TYPE2' is present here so not interested
"someOtherAttribute" : "testValue1"
},
{
"type": null,
"someOtherAttribute" : "testValue2"
}
]
}
{
"myShoppingList": [
{
"someOtherAttribute" : "testValue1" // no type value present
},
{
"type": null,
"someOtherAttribute" : "testValue1" // and type is null here
}
]
}
{
"myShoppingList": [] // empty list should be ignored
}

这需要是一个由两部分组成的查询,用于评估每个单独的数组元素(即$elemMatch(:

  • 至少有一个字段不等于TYPE2且不为null
  • 没有等于TYPE2的字段

在查找查询中,可能看起来像:

db.collection.find({
myShoppingList: {
$elemMatch: {
$and: [
{"type": {$ne: "TYPE2"}},
{"type": {$ne: null}}
]
},
$not: {$elemMatch: {type: "TYPE2"}}
}
})

游乐场

最新更新