Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update array element by id with mongo query

Tags:

mongodb

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

like image 838
boneash Avatar asked Nov 28 '13 09:11

boneash


People also ask

How do you update an array element in MongoDB?

You can use the updateOne() or updateMany() methods to add, update, or remove array elements based on the specified criteria. It is recommended to use the updateMany() method to update multiple arrays in a collection.

Can we update ID in MongoDB?

You cannot update it but you can save a new id and remove the old id.

What is find by ID and update in MongoDB?

MongoDB provides a few methods for updating data. One of these method is findByIdAndUpdate() method. The findByIdAndUpdate() method matches a single document and then updates it. This method needs a string value, which is the value of the _id field.


1 Answers

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.

like image 125
Parvin Gasimzade Avatar answered Oct 07 '22 09:10

Parvin Gasimzade