0

I have a document of this kind.

{
  "id": "5a212b985735dd44089e4782",
  "people": [
    {
      "personId": "5a212b985735dd44089e4783",
      "name": "Ronaldo",
      "parents": [
        {
          "parentId": "5a212b985735dd44089e4784",
          "name": "Messi",
          "address": [
            {
              "addressId": "5a212b985735dd44089e4785",
              "country": "Argentina",
              "city": "Blah Blah"
            },
            {
              "addressId": "5a212b985735dd44089e4786",
              "country": "USA",
              "city": "New York"
            }
          ]
        }
      ]
    }
  ]
}

I have to replace the exiting parent object inside the parents array with a new parent object.

The code I have written is:

Query query = new Query(Criteria.where("id").is("5a212b985735dd44089e4782"));
Update update = new Update().push("people.$.parents", parent);
this.mongoTemplate.findAndModify(query, update, PeopleInfo.class);

However, instead of replacing the existing parent object, it is creating a new one.

Does anyone know how to perform a query of this kind?

Maelig
  • 2,046
  • 4
  • 24
  • 49
Rokin Maharjan
  • 629
  • 7
  • 19
  • 1
    Multiple positional operator supported in 3.6. You can try `db.collection_name.update( {_id: "5a212b985735dd44089e4782" }, { $set: { "people.$[p].parents.$[pp]": parent } }, { arrayFilters: [ { 'p.name': "Ronaldo" }, { "pp.name": "Messi" } ] } )` in shell. More info [here](https://stackoverflow.com/questions/23577123/updating-a-nested-array-with-mongodb) – s7vr Dec 20 '17 at 19:00

1 Answers1

0

Do read documentation for push here. What you should do in this case is set not push

Query query = new Query(Criteria.where("id").is("5a212b985735dd44089e4782"));
Update update = new Update().set("people.parents", parent);
this.mongoTemplate.findAndModify(query, update, PeopleInfo.class);
pvpkiran
  • 25,582
  • 8
  • 87
  • 134