db.collection_name.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
}
)
> 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.lmcjl.com/mongodb/index.html"}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.course.find().pretty() { "_id" : ObjectId("603209d8e492ab9be9450304"), "title" : "MongoDB教程", "author" : "编程帮", "url" : "http://www.lmcjl.com/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.lmcjl.com/mongodb/index.html"}},{multi:true})
db.collection_name.save(
<document>,
{
writeConcern: <document>
}
)
> db.course.save( ... { ... "_id" : ObjectId("603209d8e492ab9be9450304"), ... "title" : "MongoDB教程", ... "description" : "MongoDB 是一个 Nosql 数据库", ... "author" : "编程帮", ... "url" : "http://www.lmcjl.com/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.lmcjl.com/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" }
本文链接:http://task.lmcjl.com/news/7286.html