MongoDB $unset 如果满足条件

MongoDB $unset If condition is met

有人能帮我解决这个问题吗?

我有这个假的JSON...

[
  {
    "user": {
      "type": "PF",
      "code": 12345,
      "Name": "Darth Vader",
      "currency": "BRL",
      "status": "ACTIVE",
      "localization": "NABOO",
      "createDate": 1627990848665,
      "olderAdress": [
        {
          "localization": "DEATH STAR",
          "status": "BLOCKED",
          "createDate": 1627990848665
        },
        {
          "localization": "TATOOINE",
          "status": "CANCELLED",
          "createDate": 1627990555665
        },
        {
          "localization": "ALDERAAN",
          "status": "INACTIVED",
          "createDate": 1627990555665
        },
        
      ]
    }
  }
]

如果状态等于“已阻止”或“已取消”,我想删除字段 code。我正在使用聚合,因为我在 Practical Example 之前做了很多事情。我该怎么做?

我需要这个结果:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "user": {
      "Name": "Darth Vader",
      "createDate": 1.627990848665e+12,
      "currency": "BRL",
      "localization": "DEATH STAR",
      "status": "BLOCKED",
      "type": "PF"
    }
  },
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "user": {
      "Name": "Darth Vader",
      "createDate": 1.627990555665e+12,
      "currency": "BRL",
      "localization": "TATOOINE",
      "status": "CANCELLED",
      "type": "PF"
    }
  },
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "user": {
      "Name": "Darth Vader",
      "code": 12345,
      "createDate": 1.627990555665e+12,
      "currency": "BRL",
      "localization": "ALDERAAN",
      "status": "INACTIVED",
      "type": "PF"
    }
  },
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "user": {
      "Name": "Darth Vader",
      "code": 12345,
      "createDate": ISODate("2021-09-16T17:36:26.405Z"),
      "currency": "BRL",
      "localization": "NABOO",
      "status": "ACTIVE",
      "type": "PF"
    }
  }
]

Soo...独立于名称,我将检查状态,如果您考虑到该条件,我将删除该字段 code

查询

  • 使用系统变量 $$REMOVE 如果一个字段得到这个值它被删除
  • 所以条件是 user.code ,如果不是 "BLOCKED","CANCELLED" 则保留旧值,否则 "$$REMOVE" 字段

Test code here

db.collection.aggregate([
  {
    "$set": {
      "user.code": {
        "$cond": [
          {
            "$in": [
              "$user.status",
              [
                "BLOCKED",
                "CANCELLED"
              ]
            ]
          },
          "$$REMOVE",
          "$user.code"
        ]
      }
    }
  }
])

编辑

上面的代码检查 user.status 但你想删除代码或不基于 user.olderAdress.status (展开后) (其 2 个具有相同名称状态的字段)

查询(在您已有的阶段之后添加)

Test code

{
    "$set": {
      "user.code": {
        "$cond": [
          {
            "$in": [
              "$user.status",
              [
                "BLOCKED",
                "CANCELLED"
              ]
            ]
          },
          "$$REMOVE",
          "$user.code"
        ]
      }
    }
  }