Mongodb 查找数组中某个属性为空的所有条目

Mongodb 查找数组中某个属性为空的所有条目,mongodb,Mongodb,我有以下mongodb查询: db .getCollection("entries") .find({ $and: [ { "array.attribute_1": { $exists: true, $not: { $size: 0 } } }, { $or: [ { "array.attribute_

我有以下mongodb查询:

db
.getCollection("entries")
.find({
    $and: [
      {
        "array.attribute_1": {
          $exists: true,
          $not: {
            $size: 0
          }
        }
      },
      {
        $or: [
          { "array.attribute_2": { $exists: true, $size: 0 } },
          { "array.attribute_2": { $exists: true, $eq: {} } }
        ]
      },
    ]
})
以及我的文档的示例:

{
    _id: 'foo',
    array: [
       {attribute_1: [], attribute_2: []}, 
       {attribute_1: ['bar'], attribute_2: []}
    ]
}
根据我的理解,我的查询应该找到所有
条目
,这些条目在
数组
中至少有一个元素,该元素存在且不为空
属性_1
和存在的空数组或空对象
属性_2
。但是,此查询将查找所有
条目
,这些条目在
数组
中包含所有元素,这些元素存在且不为空
属性_1
和存在的空数组或空对象
属性_2
。因此,将找不到我的
foo
条目


对于我的要求,正确的公式应该是什么?

$find
将找到符合匹配条件的第一个文档,在您的情况下,第一个文档包含所有数组。您需要将
$project
$filter
一起使用,或者将聚合与
$unwind
$match
一起使用

大概是这样的:

db.collection.aggregate([
  { $unwind: "$array" },
  {
    $match: {
      $and: [
        { "array.attribute_1.0": { $exists: true }},
        {
          $or: [
            { "array.attribute_2.0": { $exists: false } },
            { "array.attribute_2.0": { $eq: {} } }
          ]
        }
      ]
    }
  }
])
你可以看到它在工作


另外,由于您正在尝试使用
.0
$exists
来确定数组是否为空并且是否同时存在,因此,使用
$exists
$size
可以快速且简单地获得相同的结果

不幸的是,
.0
不起作用,因为
属性_2
可以是一个对象,但感谢您提醒我注意
$unwind
,因为它正是需要的