The update() method updates the values in the existing document.
Syntax
The basic syntax of update() method is as follows −
>db.getCollection(COLLECTION_NAME).update(SELECTION_CRITERIA, UPDATED_DATA)
Example
Assume the collection has the following data.
{ "_id" : ObjectId(5), "title":"MongoDB OV"}
The following example will set the new title 'MongoDB Tut' of the documents whose title is 'MongoDB OV'.
{ "_id" : ObjectId(6), "title":"NoSQL OV"}
{ "_id" : ObjectId(7), "title":"AOQ OV"}
>db.getCollection(COLLECTION_NAME).update({'title':'MongoDB OV'},{$set:{'title':'MongoDB Tut'}})
>db.getCollection(COLLECTION_NAME).find()
{ "_id" : ObjectId(5), "title":"MongoDB Tut"}
{ "_id" : ObjectId(6), "title":"NoSQL OV"}
{ "_id" : ObjectId(7), "title":"AOQ OV"}
By default, MongoDB will update only a single document. To update multiple documents, you need to set a parameter 'multi' to true.
>db.getCollection(COLLECTION_NAME).update({'title':'MongoDB OV'},
{$set:{'title':'MongoDB Tut'}},{multi:true})
Example
Operation | Syntax | Example | RDBMS Equivalent |
---|---|---|---|
Equality | {<key>:<value>} | db.getCollection(COLLECTION_NAME).find({"by": AOQ})
db.getCollection(COLLECTION_NAME).find({"by": /AOQ/}) |
where 'by' = 'AOQ'
where 'by' like '%AOQ%' |
Less Than | {<key>:{$lt:<value>}} | db.getCollection(COLLECTION_NAME).find({"likes":{$lt:10}}) | where 'likes' < 10 |
Less Than or Equal | {<key>:{$lte:<value>}} | db.getCollection(COLLECTION_NAME).find({"likes":{$lte:10}}) | where 'likes' <= 10 |
Greater Than | {<key>:{$gt:<value>}} | db.getCollection(COLLECTION_NAME).find({"likes":{$gt:10}}) | where 'likes' > 10 |
Greater Than or Equal | {<key>:{$gte:<value>}} | db.getCollection(COLLECTION_NAME).find({"likes":{$gte:10}}) | where 'likes' >= 10 |
Not Equal | {<key>:{$ne:<value>}} | db.getCollection(COLLECTION_NAME).find({"likes":{$ne:10}}) | where 'likes' != 10 |
Example
Operation | Syntax | Example |
---|---|---|
AND | db.getCollection(COLLECTION_NAME).find( { $or: [ {key1: value1}, {key2:value2} ] } ) | db.getCollection(COLLECTION_NAME).find( { $and: [ {key1: value1}, {key2:value2} ] } ) |
OR | db.COLLECTION_NAME.find( { $or: [ {key1: value1}, {key2:value2} ] } ) | db.getCollection(COLLECTION_NAME).find( { $or: [ {key1: value1}, {key2:value2} ] } ) |
AND and OR simultaneously | db.getCollection(COLLECTION_NAME).find({"key7": {$gt:Value7a}, $or: [{"key4": "value4"},
{"key2": "value2"}]})
Returns: { "key1": Value1, "key2": "Value2", "key3": "Value3", "key4": "Value4", "key5": "Value5", "key6": ["Value6a", "Value6b", "Value6c"], "key7": "Value7b" } |
db.getCollection(COLLECTION_NAME).find({"likes": {$gt:10}, $or: [{"by": "AOQ"},
{"title": "MongoDB OV"}]})
Returns: { "_id": ObjectId(c), "title": "MongoDB OV", "description": "MongoDB descr", "by": "AOQ", "url": "http://www.armyofquants.com", "tags": ["MongoDB", "DB", "NoSQL"], "likes": "500" } |