MongoDB:更新数组中的元素,其中元素的索引保存在文档中

jhkqcmku  于 2022-12-12  发布在  Go
关注(0)|答案(1)|浏览(165)

我的文档结构如下。

{
    _id: ...,
    unique_id: 1234,
    config_no: 1,
    configs: [
        {
            data: "qwertyuiop" // random string
        },
        {
            data: "asdfghjkl" // random string
        }
    ]
}

我想从其中一个configs更新data的值。需要更新的config的索引在config_no键中可用。
是否有任何方法可以在不查询文档的情况下更新该值。
这是我目前正在做的事情

doc = db.collection.findOne({"unique_id": 1234})
config_no = doc.config_no
db.collection.updateOne(
    {"unique_id": 1234},
    {"$set": {"configs."+config_no+".data": "zxcvbnm"}} //"configs.1.data"
)

以下是我想达到的目标。

db.collection.updateOne(
    {"unique_id": 1234},
    {"$set": {"configs.${config_no}.data": "zxcvbnm"}}
)
0g0grzrc

0g0grzrc1#

可以使用includeArrayIndex选项$unwind.使用索引执行条件更新并将$merge放回集合中。

db.collection.aggregate([
  {
    $match: {
      unique_id: 1234
    }
  },
  {
    "$unwind": {
      path: "$configs",
      includeArrayIndex: "idx"
    }
  },
  {
    $set: {
      "configs.data": {
        "$cond": {
          "if": {
            $eq: [
              "$config_no",
              "$idx"
            ]
          },
          "then": "zxcvbnm",
          "else": "$configs.data"
        }
      }
    }
  },
  {
    $group: {
      _id: "$_id",
      config_no: {
        $first: "$config_no"
      },
      configs: {
        $push: "$configs"
      },
      unique_id: {
        $first: "$unique_id"
      }
    }
  },
  {
    "$merge": {
      "into": "collection",
      "on": "_id",
      "whenMatched": "merge"
    }
  }
])

Mongo Playground

相关问题