📜  MongoDB更新文档

📅  最后修改于: 2020-11-23 01:15:55             🧑  作者: Mango

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" }