skip to Main Content

I’m dealing with a mongo database and my table looks like this.
currently to update everything I use the save method passing it a bean but it doesn’t work if I have to update only one element of the array as it overwrites the whole record.

{
"_id" : "21",
"idVlt" : "187",
"giochi" : [
    {
        "_id" : "22",
        "installed" : "true",
        "enable" : "true",
        "urlimg" : "placeholder.png",
        "categories" : [

        ],
        "tags" : [

        ]
    },
    {
        "_id" : "151",
        "installed" : "true",
        "enable" : "false",
        "urlimg" : "placeholder.png",
        "categories" : [

        ],
        "tags" : [

        ]
    },
    {
        "_id" : "197",
        "installed" : "true",
        "enable" : "false",
        "urlimg" : "placeholder.png",
        "categories" : [

        ],
        "tags" : [

        ]
    }
],

}

I would like to understand how I can update the element of the array with _id:22 : "installed":"true" –> false

and being able to insert a new element into the array :

 {
    "_id" : "222",
    "installed" : "true",
    "enable" : "true",
    "urlimg" : "placeholder.png",
    "categories" : [

    ],
    "tags" : [

    ]
}

with db.AssociazioneGameVlt.find({ $and: [ {"giochi._id":"77"}] })
i’ve Resutl

2

Answers


  1. Chosen as BEST ANSWER

    Thanks, i try it on my mongodb and it's ok.... now i traslate it in code java like this

    Query query = new Query(Criteria.where("idVlt").is("148"));
          query.addCriteria(Criteria.where("giochi._id").is("197"));
          System.out.println("query : "+query);
          var update = Update.update("giochi.$.installed", "148_197");
          System.out.println("update : "+update);
          mongoTemplate.findAndModify(query, update,AssociazioneGameVlt.class );
    

    But i've this error : org.springframework.data.mongodb.UncategorizedMongoDbException: Command failed with error 2 (BadValue): 'The positional operator did not find the match needed from the query.' on server...

    however, if I put '0' instead of '$' it modifies the first element of the array instead of getting the correct one


  2. To update the element in the giochi array with the _id: "22" you can use the following update query:

    db.collection.update({
      "_id": "21",
      "giochi._id": "22"
    },
    {
      $set: {
        "giochi.$.installed": "false"
      }
    })
    

    And to add a new element you can use below

    db.collection.update(
       { "_id": "21" },
          { $push: { "giochi": {
              "_id" : "222",
              "installed" : "true",
              "enable" : "true",
              "urlimg" : "placeholder.png",
              "categories": [],
              "tags": []
            } }
          }
        )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search