mongodb 管道 $filter 条件不是 $in

问题描述 投票:0回答:1

我想使用管道通过过滤对象中子文档的键来更新文档。

例如数据:

{
  things: {
    a1: {},
    ...
    x1: {}
  }
}

“事物”可以包含变量键/属性。 我知道我可以使用这样的更新管道,其中“keepKeys”是我想保留在“things”对象中的键:

[ 
  $set: {
    things: { 
      $arrayToObject: {
        $filter: {
          "input": {
            $objectToArray: "$$ROOT.things"
          },
          "as": "item",
          "cond": {
             "$in": [
               "$$item.k",
               keepKeys
             ]
          }
        }
     }
  } 
]

这可行,但我宁愿过滤掉我不想要的东西,因为这是一个更短的列表,例如,其中discardKeys是我不想要的键:

[ 
  $set: {
    things: { 
      $arrayToObject: {
        $filter: {
          "input": {
            $objectToArray: "$$ROOT.things"
          },
          "as": "item",
          "cond": {
             "$nin": [
               "$$item.k",
               discardKeys
             ]
          }
        }
     }
  } 
]

但是管道$filter cond不支持$nin

mongodb mongodb-query mongodb-update
1个回答
0
投票

您可以使用

$indexOfArray
来检查discardKeys中的密钥是否不存在。因为当未找到元素时
$indexOfArray
返回
-1

所以如果

discardKeys = ["x1", "x2", "a3" ]
:

db.collection.aggregate([
  {
    $set: {
      things: {
        $arrayToObject: {
          $filter: {
            "input": {
              $objectToArray: "$$ROOT.things"
            },
            "as": "item",
            "cond": {
              $eq: [
                { $indexOfArray: [["x1", "x2", "a3"], "$$item.k"] },
                -1
              ]
            }
          }
        }
      }
    }
  }
])

蒙戈游乐场

© www.soinside.com 2019 - 2024. All rights reserved.