Mongoose - Return 仅当条件匹配数组中的所有对象时才对象

Mongoose - Return object only if condition matches all the objects in array

描述:

我只想 return 如果数组中的所有对象都符合条件。现在,如果对象数组中至少有一个条件匹配,它就会 return 对象。

如果大家对这个问题还有什么疑问。我会回答请问!

输入:

[
   {
      "_id":"4",
      "intends":[
         {
            "_id":"1",
            "status":"Packed"
         },
         {
            "_id":"2",
            "status":"Packed"
         }
      ]
   },
   {
      "_id":"5",
      "intends":[
         {
            "_id":"3",
            "status":"Packed"
         },
         {
            "_id":"4",
            "status":"Created"
         }
      ]
   }
]

当前输出:

[
   {
      "_id":"4",
      "intends":[
         {
            "_id":"1",
            "status":"Packed"
         },
         {
            "_id":"2",
            "status":"Packed"
         }
      ]
   },
   {
      "_id":"5",
      "intends":[
         {
            "_id":"3",
            "status":"Packed"
         },
         {
            "_id":"4",
            "status":"Created"
         }
      ]
   }
]

预期输出:

[
   {
      "_id":"4",
      "intends":[
         {
            "_id":"1",
            "status":"Packed"
         },
         {
            "_id":"2",
            "status":"Packed"
         }
      ]
   }
]

我试过:

db.collection.find({intends.status: "Packed"})
db.collection.find({intends: {$elemMatch: {status: "Packed"}}})

使用 $elemMatch$nin$not 的可能解决方案。
$elemMatch$nin 部分将提供所有元素,其中至少有一个元素的状态不是“已打包”。所以 $not 将反转它并给出每个状态都是“已打包”的元素

db.collection.find({
  intends: {
    "$not": {
      "$elemMatch": {
        status: {
          "$nin": [
            "Packed"
          ]
        }
      }
    }
  }
})

demo

更新 因为这里只是检查 1 个值,所以使用 $ne 而不是 $nin

db.collection.find({
  intends: {
    $not: {
      $elemMatch: {
        status: {
          $ne: "Packed"
        }
      }
    }
  }
})

demo

使用 aggregation $redact and $allElementsTrue

mongoPlayground

进行测试
db.collection.aggregate([
  {
    "$redact": {
      "$cond": [
        {
          "$allElementsTrue": {
            "$map": {
              "input": "$intends",
              "as": "intend",
              "in": {
                "$eq": [
                  "$$intend.status",
                  "Packed"
                ]
              }
            }
          }
        },
        "$$KEEP",
        "$$PRUNE"
      ]
    }
  }
])