365Tools
发布时间:2024-03-29 12:30:01
在 MongoDB 中,可以使用 update() 和 save() 方法来更新集合中的文档。其中 update() 方法可以更新现有文档中的值,而 save() 方法则可以使用传入文档来替换已有文档。
db.collection_name.update(
{
upsert:
multi:
writeConcern:
}
)
> db.course.insert([
... {
... title: 'MongoDB教程',
... author: '编程帮',
... url: 'http://www.biancheng.com/'
... },{
... title: 'HTML教程',
... author: '编程帮',
... url: 'http://www.biancheng.com/html/index.html'
... },{
... title: 'C#教程',
... author: '编程帮',
... url: 'http://www.biancheng.com/csharp/index.html'
... }
... ])
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 3,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
接着使用 update() 方法修改 title 为“MongoDB教程”的文档中的内容。
> db.course.update({title:"MongoDB教程"},{$set:{url:"http://www.www.365tools.cn/mongodb/index.html"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.course.find().pretty()
{
"_id" : ObjectId("603209d8e492ab9be9450304"),
"title" : "MongoDB教程",
"author" : "编程帮",
"url" : "http://www.www.365tools.cn/mongodb/index.html"
}
{
"_id" : ObjectId("603209d8e492ab9be9450305"),
"title" : "HTML教程",
"author" : "编程帮",
"url" : "http://www.biancheng.com/html/index.html"
}
{
"_id" : ObjectId("603209d8e492ab9be9450306"),
"title" : "C#教程",
"author" : "编程帮",
"url" : "http://www.biancheng.com/csharp/index.html"
}
默认情况下,在使用 update() 方法更新文档时仅会更新一个文档,若想要更新多个文档,您则需要将参数“multi”设置为 true,如下所示:db.course.update({title:"MongoDB教程"},{$set:{url:"http://www.www.365tools.cn/mongodb/index.html"}},{multi:true})
db.collection_name.save(
{
writeConcern:
}
)
> db.course.save(
... {
... "_id" : ObjectId("603209d8e492ab9be9450304"),
... "title" : "MongoDB教程",
... "description" : "MongoDB 是一个 Nosql 数据库",
... "author" : "编程帮",
... "url" : "http://www.www.365tools.cn/mongodb/index.html",
... "likes" : 996
... }
... )
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
更新成功后您可以使用 find() 方法来查看更新后的数据。
> db.course.find().pretty()
{
"_id" : ObjectId("603209d8e492ab9be9450304"),
"title" : "MongoDB教程",
"description" : "MongoDB 是一个 Nosql 数据库",
"author" : "编程帮",
"url" : "http://www.www.365tools.cn/mongodb/index.html",
"likes" : 996
}
{
"_id" : ObjectId("603209d8e492ab9be9450305"),
"title" : "HTML教程",
"author" : "编程帮",
"url" : "http://www.biancheng.com/html/index.html"
}
{
"_id" : ObjectId("603209d8e492ab9be9450306"),
"title" : "C#教程",
"author" : "编程帮",
"url" : "http://www.biancheng.com/csharp/index.html"
}