Random MongoDb Syntax: Updates

Posted by Liam McLennan on Geeks with Blogs See other posts from Geeks with Blogs or by Liam McLennan
Published on Tue, 01 Jun 2010 18:15:03 GMT Indexed on 2010/06/02 0:34 UTC
Read the original article Hit count: 285

Filed under:

I have a MongoDb collection called tweets. Each document has a property system_classification. If the value of system_classification is ‘+’ I want to change it to ‘positive’.

For a regular relational database the query would be:

update tweets
set system_classification = 'positive'
where system_classification = '+'

the MongoDb equivalent is:

 db.tweets.update({system_classification: '+'}, 
 {$set: {system_classification:'positive'}}, false, true)

Parameter Description

{ system_classification: '+' }

the first parameter identifies the documents to select

{ $set: { system_classification: 'positive' } }

the second parameter is an operation ($set) and the parameter to that operation {system_classification: ‘positive’}
false the third parameter indicates if this is a regular update or an upsert (true for upsert)
true the final parameter indicates if the operation should be applied to all selected documents (or just the first)

© Geeks with Blogs or respective owner