Updating an array element by ID using mongo request

Is there a request to update sc from 15 to say 17 for an array element with id 2 for _id 1? I have this structure in mongodb:

  { _id: 1,
    lb: [
       {
          id: 2,
          sc: 15
       },
       {
          id: 3,
          sc: 16
       }
        ]
  }
  { _id: 2,
    lb: [
       {
          id: 5,
          sc: 34
       },
       {
          id: 6,
          sc: 12
       }
        ]
  }

I have one more: is there a way to write a request for an update, as you just said, and if there is no array element with an updated identifier, insert a new one. I do not want to make two requests - first check if the element exists and update it, and then add it if there is none. It would be nice to add it to one query. Thank you - user3045201 1 hour ago

+4
source share
1 answer

You can update it using the following query:

db.myCollection.update({"_id" : 1, "lb.id" : 2},{$set : {"lb.$.sc" : 17}})

AFAIK. , . .

+12

All Articles