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" }
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.
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" }
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With