Difference between revisions of "MongoDB Update"

From mi-linux
Jump to navigationJump to search
Line 35: Line 35:
 
Update department 40 to change the location to Wolverhampton:
 
Update department 40 to change the location to Wolverhampton:
  
  db.deptCollection.update({'deptno':40},  
+
  db.dept.update({'deptno':40},  
 
   {$set:  {'loc': 'WOLVERHAMPTON'}})
 
   {$set:  {'loc': 'WOLVERHAMPTON'}})
  
 
Check the changes have been made:
 
Check the changes have been made:
  
  db.deptCollection.find({"deptno":40}).pretty()
+
  db.dept.find({"deptno":40}).pretty()
 
 
  
 
=== Updating the emp collection ===
 
=== Updating the emp collection ===

Revision as of 16:06, 12 November 2017

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

Updating a Collection

The format of the update command is:

 db.collectionName.update({'keyField': 'value' }, 
  {$set: field: 'newValue' }
 )

The update() function can be used to update one or more documents. If the change should only apply to one document, the keyField needs to be a field with unique values, to ensure the correct document is updated.

This is similar in SQL to providng 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.replaceOne(); /* replaces the first document that matches a specified filter             
                                    (even if several documents match the filter) */


Updating the dept collection

Update department 40 to change the location to Wolverhampton:

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

Check the changes have been made:

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

Updating the emp collection

Exercise 2.2

  • 2.2.1 Update the name of department 40 to: COMPUTING
  • 2.2.1 Update the salary of employee number 7788 in department 20 to 3500

Next Step

Deleting a document, or collection.