Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update record in MongoDB without replacing the existing fields?

When I am update a record, it removes the existing fields and adds the new ones.

This was the record before the update:

{ "_id" : ObjectId("56a356863aa433ae37dc2cee"), "browser" : "Chrome", "version" : 47}

This was the command I executed:

db.collection('profiles')
  .update({ 
    '_id' : obj("56a356863aa433ae37dc2cee") }, 
    {"first_name" : first_name, "last_name" : last_name, "email" : email}, 
    function (err, result) {
      console.log(result);
  });

This was the record after I had executed the update command:

{ "_id" : ObjectId("56a356c9a08487ed3719e40a"), "first_name" : "kaushik", "last_name" : "makwana", "email" : "kdmakwana" }
like image 711
Kaushik Makwana Avatar asked Jan 23 '16 11:01

Kaushik Makwana


People also ask

Is it possible to update MongoDB field using value of another field?

Starting from MongoDB 4.2 you can perform Updates with an Aggregation Pipeline. An aggregation pipeline enables more expressive updates including calculated fields and references to other field values in the same document.


2 Answers

Same as the updating existing collection field, $set will add a new fields if the specified field does not exist.

> db.foo.find()
> db.foo.insert({"test":"a"})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> item = db.foo.findOne()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> db.foo.update({"_id" :ObjectId("4e93037bbf6f1dd3a0a9541a") },{$set : {"new_field":1}})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "new_field" : 1, "test" : "a" }
like image 124
null1941 Avatar answered Oct 26 '22 13:10

null1941


use $set to update fields or add new fields. Your query should be:

db.collection('profiles').update(
    { 
    '_id' : obj("56a356863aa433ae37dc2cee")
    },
    { $set:{{"first_name" : first_name, "last_name" : last_name, "email" : email}} }, 

    function (err, result){
        console.log(result); 
    });
like image 33
Ikrum Hossain Avatar answered Oct 26 '22 14:10

Ikrum Hossain