如何更新 mongodb 中的数组值?

How can i update array value in mongodb?

例如,

{
    "_id":ObjectId("6245131fdbcda3639d75c951"),
    "username": "joy"
    "data" : [ 
        {
            "_id" : ObjectId("6245131fdbcda3639d75c953"),
            "value_1" : "hello1"
            "value_2" : "thank you1"
        }, 
        {
            "_id" : ObjectId("6245131fdbcda3639d75c954"),
            "value_1" : "hello2"
            "value_2" : "thank you2"
        }, 

    ]
}

我想编辑其中一个数据对象并删除旧的并推送编辑过的一个

因为我想编辑的对象将是数组的最后一个索引。

我想得到这个结果。

{
    "_id":ObjectId("6245131fdbcda3639d75c951"),
    "username": "joy"
    "data" : [ 
        {
            "_id" : ObjectId("6245131fdbcda3639d75c954"),
            "value_1" : "hello2"
            "value_2" : "thank you2"
        }, 
        {
            "_id" : ObjectId("6245131fdbcda3639d75c953"),
            "value_1" : "change data from hello1"
            "value_2" : "change data from thank you1"
        }, 

    ]
}

我试过了,但出现错误。

db.getCollection('profile').update(
{username:"joy"},
{
  {
    "$pull": {"data": 
                    {"_id": ObjectId("6245131fdbcda3639d75c953")}
    },
  },
  {
    "$push": {"data": 
       {
       "_id" : ObjectId("6245131fdbcda3639d75c953"),
       "value_1" : "change data from hello1"
       "value_2" : "change data from thank you1"
       }
     },
  }
})

如何获取值? 谢谢你。 :)

MongoDB将不允许在单个字段中使用多个operations/operators,从4.2开始可以使用update with aggregation pipeline

  • $filter 迭代 data 数组的循环并过滤不等于您输入的文档 _id,
  • $concatArrays 连接过滤后的 data 数组和要添加到 data 数组
  • 的最后一个索引中的新对象
db.getCollection('profile').update(
  { username: "joy" },
  [{
    $set: {
      data: {
        $concatArrays: [
          {
            $filter: {
              input: "$data",
              cond: {
                $ne: ["$$this._id", "6245131fdbcda3639d75c953"]
              }
            }
          },
          [
            {
              _id: "6245131fdbcda3639d75c953",
              value_1: "change data from hello1",
              value_2: "change data from thank you1"
            }
          ]
        ]
      }
    }
  }]
)

Playground