如何更新数组对象中的第一个元素

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

我的文件是

{
  _id: 1,
  age: "young",
  hobby: [
  {
    vehicle: "car",
    velocity: "fast"
  },
  {
    vehicle: "motorcycle",
    velocity: "fast"
  }
  ]
}

我的目标是:当年龄变老时,第一个爱好变得“慢”,但其他爱好仍然“快”

我的代码是:

mongoTemplate.updateFirst(
  Query.query(where("_id").is("1")),
    Update.update("age", "old")
      .set("hobby.$[elem].velocity", "slow")
      .filterArray(Criteria.where("elem").is(0)), "collection name")

但是不行,结果是:

{
  _id: 1,
  age: "old",
  hobby: [
  {
    vehicle: "car",
    velocity: "fast"  <<--- not slow
  },
  {
    vehicle: "motorcycle",
    velocity: "fast"
  }
  ]
}

我可以通过

实现我的目标
mongoTemplate.updateFirst(
  Query.query(where("_id").is("1111")),
    Update.update("age", "old")
      .set("hobby.$[elem].velocity", "slow")
      .filterArray(Criteria.where("elem.vehicle").is("car")), "collection name")

但我想修改 FIRST 数组元素,而不是 car 数组元素

spring mongodb
1个回答
0
投票

如果你总是只想更新第一个元素,那么你可以用 0 引用

第一个元素
。标准查询是:

db.collection.update({ _id: 1111 },
{
  $set: {
    "age": "old",
    "hobby.0.velocity": "slow"  // note the '0'
  }
})

蒙戈游乐场

我不知道,但我认为查询会是这样的:

mongoTemplate.updateFirst(
  Query.query(where("_id").is("1111")),
    Update.update("age", "old")
      .set("hobby.0.velocity", "slow")  // note the '0'
© www.soinside.com 2019 - 2024. All rights reserved.