Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to update first element in array object

My document is

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

My goal is: when age became old, first hobby became "slow" but others remain "fast"

My code is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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")

But it does not work, result is:

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

I could achieve my goal with

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")

But I want modify FIRST array element, not car array element

>Solution :

If you always only want to update the first element, then you can refer to the first element with 0. The standard query would be:

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

Mongo Playground

I don’t know but I presume the query would be something like:

mongoTemplate.updateFirst(
  Query.query(where("_id").is("1111")),
    Update.update("age", "old")
      .set("hobby.0.velocity", "slow")  // note the '0'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading