15

Is there a query to update sc from 15 to let's say 17 for array element with id 2 for _id 1? I've 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 query to update as you just said and if there is no array element with updated id, insert a new one. I don't want to make two queries - first to check if element exist and update it, second to append it if there is no such. It would be nice to append it in one query. Thanks. – user3045201 1 hour ago

boneash
  • 158
  • 1
  • 3
  • 19

1 Answers1

38

You can update it using the following query :

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

AFAIK, It is not possible to do what you want in a single query. You have to make seperate queries for each of them.

Parvin Gasimzade
  • 25,180
  • 8
  • 56
  • 83