HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
MongoDB usingupdate () and save ()method to update the collection of documents. Let's take a detailed look at the application and the difference between the two functions.
update () method is used to update an existing document. Syntax is as follows:
db.collection.update( <query>, <update>, { upsert: <boolean>, multi: <boolean>, writeConcern: <document> } )
Parameter Description:
We insert the following data collection col:
>db.col.insert({ title: 'MongoDB 教程', description: 'MongoDB 是一个 Nosql 数据库', by: '本教程', url: 'https://w3resource.net', tags: ['mongodb', 'database', 'NoSQL'], likes: 100 })
Then we have to update the title by the update () method (title):
>db.col.update({'title':'MongoDB 教程'},{$set:{'title':'MongoDB'}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) # 输出信息 > db.col.find().pretty() { "_id" : ObjectId("56064f89ade2f21f36b03136"), "title" : "MongoDB", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "本教程", "url" : "https://w3resource.net/", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 } >
You can see the title (title) from the original "MongoDB Tutorial" Update to "MongoDB."
The above statement will modify the document found in the first, if you want to edit the same document and more, you need to set multi parameter to true.
>db.col.update({'title':'MongoDB 教程'},{$set:{'title':'MongoDB'}},{multi:true})
save () method by passing documents to replace the existing document. Syntax is as follows:
db.collection.save( <document>, { writeConcern: <document> } )
Parameter Description:
The following example we replaced the _id as 56064f89ade2f21f36b03136 document data:
>db.col.save({ "_id" : ObjectId("56064f89ade2f21f36b03136"), "title" : "MongoDB", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "w3resource", "url" : "https://w3resource.net/", "tags" : [ "mongodb", "NoSQL" ], "likes" : 110 })
After the replacement is successful, we can () command to view the data after replacement by find
>db.col.find().pretty() { "_id" : ObjectId("56064f89ade2f21f36b03136"), "title" : "MongoDB", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "w3resource", "url" : "https://w3resource.net/", "tags" : [ "mongodb", "NoSQL" ], "likes" : 110 } >
Only update the first record:
Update all:
Add only the first:
Add all added:
Update all:
Only update the first record: