Mongoose - 只在条件匹配数组中的所有对象时返回对象

5

描述:

我希望当数组中的所有对象都匹配条件时,只返回结果。现在,如果数组中至少有一个条件匹配,则会返回该对象。

如果您对此问题有更多疑问,请随时提出!

输入:

[
   {
      "_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"}}})

1
所以您需要记录每个intends值的状态为Packed的时间戳? - cmgchess
我确切地想要那个。我也发布了期望的结果。 - dinesh oz
请注意,我已经尝试使用$elemMatch... 请查看更新后的问题。 - dinesh oz
1
更新答案。由于您只搜索一个值,请使用“ne”而不是“nin”。 - cmgchess
2个回答

3
使用$elemMatch$nin$not的可能解决方案。
$elemMatch$nin部分将给出所有具有至少一个状态不为“Packed”的元素。因此,$not将反转它,并给出每个状态都是“Packed”的元素。
db.collection.find({
  intends: {
    "$not": {
      "$elemMatch": {
        status: {
          "$nin": [
            "Packed"
          ]
        }
      }
    }
  }
})

演示

更新 由于这里只检查一个值,请使用$ne代替$nin

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

演示


0

使用 聚合 $redact$allElementsTrue

mongoPlayground 上进行测试

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接