Cacomania: MongoDB: manipulating values if a "update" is not enough

Cacomania

MongoDB: manipulating values if a "update" is not enough

Guido Krömer - 12. September 2012 - Tags: , ,

Sometimes the MongoDB update function does not fit the requirements. Since JavaScript can be executed directly in the database (if it's not disabled) it can be used for more complex updates, for example. This happens without moving the data to the application and back to the database.

This small example does the same as: myColl.update({myValue: 1}, {$inc: {myValue: 1}})

db.myCollection.find({myValue: 1}).forEach(function(doc){ 
    var newValue = doc.myValue + 1;
    db.site.update({_id: doc._id}, {$set: {myValue: newValue}})  
})

This is a concrete example where tags have been saved as a comma separated string. Creating an index, for fast searching in the tags, on this field would not make sense. Converting this string field into an array of tags should solve the problem. This piece of code does this job for each site which has been tagged, for speeding up only the tags field and MongoDB's _id field gets queried from those documents.

db.sites.find({tags: { $exists: true }}, {tags: 1}).forEach(function(doc){ 
   db.site.update({_id: doc._id}, {$set: {tags : doc.tags.split(',')}})  
})