Difference between revisions of "MongoDB Update"

From mi-linux
Jump to navigationJump to search
Line 18: Line 18:
  
 
<pre style="color:blue">
 
<pre style="color:blue">
db.collectionName.updateOne();   
+
db.collectionName.updateOne();   
 
/* updates a single document that matches a specified filter (even if several documents match the filter) */
 
/* updates a single document that matches a specified filter (even if several documents match the filter) */
 
</pre>
 
</pre>
 
<pre style="color:blue">
 
<pre style="color:blue">
db.collectionName.updateMany(); /* updates all documents that matches a specified filter */
+
db.collectionName.updateMany(); /* updates all documents that matches a specified filter */
 
</pre>
 
</pre>
 
<pre style="color:blue">
 
<pre style="color:blue">
db.collectionName.replaceMany(); /* replaces  a single document that matches a specified filter (even if several documents match the filter) */
+
db.collectionName.replaceMany(); /* replaces  a single document that matches a specified filter (even if several documents match the filter) */
 
</pre>
 
</pre>
  

Revision as of 10:58, 21 October 2016

Main Page >> MongoDB >>MongoDB Workbook >> Updating Collections

Updating a Collection

The format of the update command is:

 db.collectionName.update({'KeyField': 'value' }, 
  {$set: fieldName: 'newValue' }
 )

The KeyField value is necessary to ensure only one document is updated, rather than them all!

This is similar in SQL to proving the WHERE clause of an UPDATE command.

Alternatively since version 3.2, MongoDB also supports the following functions:

db.collectionName.updateOne();  
/* updates a single document that matches a specified filter (even if several documents match the filter) */
db.collectionName.updateMany(); /* updates all documents that matches a specified filter */
db.collectionName.replaceMany(); /* replaces  a single document that matches a specified filter (even if several documents match the filter) */


Updating Department 40

To update department 40 to add an employee:

db.deptCollection.update({'deptno':40}, 
 {$set: 
   {'employees': [   
     {
      empno: 8888,
      ename: 'MARY',
      job: 'LECTURER',
      mgr: 7566,
      hiredate: new Date(),
      sal: 4000
     } 
   ]}
 }
)

Change the location to Wolverhampton:

db.deptCollection.update({'deptno':40}, 
 {$set:  {'loc': 'WOLVERHAMPTON'}})

Check the changes have been made:

db.deptCollection.find({"deptno":40}).pretty()

Exercise 2.2

  • 2.2.1 Update the name of department 40 to: COMPUTING
  • 2.2.1 Update the ename of employee number xxx to xxx

Next Step

Deleting a document.