查找数组中属性之一为空的所有条目

时间:2019-05-30 18:05:49

标签: mongodb

我正在关注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: []}
    ]
}

据我所知,我的查询应在entries中查找所有具有至少一个元素且已存在且不为空的array并且存在空数组的所有attribute_1或空对象attribute_2。但是,此查询将查找entries中所有具有 all 个元素的所有array,该元素存在且不为空attribute_1且存在空数组或空对象{{1} }。因此,找不到我的attribute_2条目。

满足我要求的正确公式应该是什么?

1 个答案:

答案 0 :(得分:1)

$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: {} } }
          ]
        }
      ]
    }
  }
])

您可以看到它在here上运行

此外,由于您尝试使用.0$exists来查找数组是否为空且是否同时存在,因此这是一种获得与两个{{ 1}}和$exists

相关问题