MongoDB 更新文档
在MongoDB中,update()方法用于更新或修改集合中现有的文档。
语法:
db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)
示例
考虑一个具有集合名称javatpoint的示例。将以下文档插入到集合中:
db.javatpoint.insert(
{
course: "java",
details: {
duration: "6 months",
Trainer: "Sonoo jaiswal"
},
Batch: [ { size: "Small", qty: 15 }, { size: "Medium", qty: 25 } ],
category: "Programming language"
}
)
成功插入后,通过以下查询检查文档:
>db.javatpoint.find()
输出:
{ "_id" : ObjectId("56482d3e27e53d2dbc93cef8"), "course" : "java", "details" :
{ "duration" : "6 months", "Trainer" : "Sonoo jaiswal" }, "Batch" :
[ {"size" : "Small", "qty" : 15 }, { "size" : "Medium", "qty" : 25 } ],
"category" : "Programming language" }
将现有课程”java”更新为”android”:
>db.javatpoint.update({'course':'java'},{$set:{'course':'android'}})
查看集合中的更新文件:
>db.javatpoint.find()
输出结果:
{ "_id" : ObjectId("56482d3e27e53d2dbc93cef8"), "course" : "android", "details" :
{ "duration" : "6 months", "Trainer" : "Sonoo jaiswal" }, "Batch" :
[ {"size" : "Small", "qty" : 15 }, { "size" : "Medium", "qty" : 25 } ],
"category" : "Programming language" }