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.
Use the operator $set
$ db.products.update({_id: 1}, {$set: {price:999}})
This operator allows you update the specified field(s).
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