Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to update a document without overwriting the existing one?

Tags:

mongodb

I'm studying how to use mongoDB.

I want to update a certain field of a document but it overwrites the whole document. How can I update only the field in a document I want to modify?

db.products.find({_id: 1})

{
    "_id" : 1.0,
    "name" : "aaa",
    "category" : "toy",
    "price" : 100.0
}

For example, I have a document like this.

db.products.update({_id: 1}, {price:999})

db.products.find({_id: 1})

{
    "_id" : 1.0,
    "price" : 999.0
}

When I update like this, I get this result. I lost name field and category field after executing update command.

like image 304
shu Avatar asked Oct 15 '25 03:10

shu


1 Answers

Use the operator $set

$ db.products.update({_id: 1}, {$set: {price:999}})

This operator allows you update the specified field(s).

like image 186
Arnold Gandarillas Avatar answered Oct 17 '25 02:10

Arnold Gandarillas