更新MongoDb中的多个内部文档

13z8s7eq  于 2022-12-26  发布在  Go
关注(0)|答案(2)|浏览(102)

在我的示例项目中,我在manager下面有雇员,Db模式是这样的;

{
  "employees": [
    {
      "name": "Adam",
      "_id": "5ea36b27d7ae560845afb88e",
      "bananas": "allowed"
    },
    {
      "name": "Smith",
      "_id": "5ea36b27d7ae560845afb88f",
      "bananas": "not-allowed"
    },
    {
      "name": "John",
      "_id": "5ea36b27d7ae560845afb88g",
      "bananas": "not-allowed"
    },
    {
      "name": "Patrick",
      "_id": "5ea36b27d7ae560845afb88h",
      "bananas": "allowed"
    }
  ]
}

本例中允许Adam吃香蕉,不允许Smith吃香蕉,如果必须将Adam吃香蕉的权限授予Smith,则需要执行两次更新操作,如下所示:

db.managers.update(
    { 'employees.name': 'Adam' },
    { $set: { 'employees.$.bananas': 'not-allowed' } }
);

以及

db.managers.update(
    { 'employees.name': 'Smith' },
    { $set: { 'employees.$.bananas': 'allowed' } }
);

是否可以在单个查询中处理此问题?

brc7rcf0

brc7rcf01#

您可以使用$map$cond根据员工的姓名对数组条目执行条件更新。$switch用于可能的案例扩展。

db.collection.update({},
[
  {
    "$set": {
      "employees": {
        "$map": {
          "input": "$employees",
          "as": "e",
          "in": {
            "$switch": {
              "branches": [
                {
                  "case": {
                    $eq: [
                      "$$e.name",
                      "Adam"
                    ]
                  },
                  "then": {
                    "$mergeObjects": [
                      "$$e",
                      {
                        "bananas": "not-allowed"
                      }
                    ]
                  }
                },
                {
                  "case": {
                    $eq: [
                      "$$e.name",
                      "Smith"
                    ]
                  },
                  "then": {
                    "$mergeObjects": [
                      "$$e",
                      {
                        "bananas": "allowed"
                      }
                    ]
                  }
                }
              ],
              default: "$$e"
            }
          }
        }
      }
    }
  }
])

Mongo Playground

p8h8hvxi

p8h8hvxi2#

db.managers.update(
   {
      $or: [
         {"employees.name": "Adam"},
         {"employees.name": "Smith"}
      ]
   },
   {
      $set: {
         "employees.$[e].bananas": {
            $cond: [{ $eq: ["$e.name", "Adam"] }, "not-allowed", "allowed"]
         }
      }
   },
   {
      arrayFilters: [{ "e.name": { $in: ["Adam", "Smith"] } }]
   }
)

相关问题