user1774890
user1774890

Reputation: 117

update query in mongo db

I am using mongodb database to save the records.

This is one sample record:

 "_id" : ObjectId("53870ed7e4b00e612650c1b8"),
"_class" : "mkcl.os.transformer.PayloadObject",
"formId" : NumberLong(50),
"dataMap" : {
    "240" : "ramanbaug",
    "241" : "1234",
    "242" : "12345678",
    "243" : "mr.joshi",
    "244" : "8308009391 ",
    "245" : "[email protected]",
    "280" : "456",
    "287" : "1234",
    "276" : "29/05/14",
    "247" : "No",
    "248" : "No",
    "249" : "Yes",
    "250" : "No",
    "251" : "Yes",
    "252" : "No"
}

Now I want to update the value of field "241". I read about the Update and FindAndModify Query. But There is no error and records are not getting updated.

Upvotes: 4

Views: 18356

Answers (2)

Lukas Liesis
Lukas Liesis

Reputation: 26423

db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>
   }
)

in the place of enter same query as you use to find that record(s), which you want to update

in the place of enter new values, like doing during insert query and there are 3 more options:

upsert = Optional. If set to true, creates a new document when no document matches the query criteria. The default value is false, which does not insert a new document when no match is found. So if your doc will not be found you will create a new one

multi = Optional. If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document. The default value is false. For additional information, see Multi Parameter.

writeConcern = Optional. A document expressing the write concern. Omit to use the default write concern.

you can read more about write concern here: http://docs.mongodb.org/manual/core/write-concern/

Single document update example:

db.people.update(
   { name: "Andy" },
   {
      name: "Andy",
      rating: 1,
      score: 1
   },
   { upsert: true }
)

check out for upsert: true, so it will create new doc if none found by name=Andy

Multi documents update example:

db.books.update(
   { stock: { $lte: 10 } },
   { $set: { reorder: true } },
   { multi: true }
)

Example with your data:

db.people.update(
   { _id: ObjectId("53870ed7e4b00e612650c1b8") },
   {
      dataMap: {
        "241": "321"
      }
   }
)

that should work.

It's all in official documentation:

http://docs.mongodb.org/manual/reference/method/db.collection.update/

Upvotes: 17

Wizard
Wizard

Reputation: 4431

db.payloadObject.update({"dataMap.241":'1234'},{$set :{"dataMap.241":'123456'}});

Upvotes: 4

Related Questions