title: Add a key to all items on a MongoDB collection
link: http://jj.isgeek.net/2011/12/add-a-key-to-all-items-on-a-mongodb-collection/
author: Jj
description: 
post_id: 823
date: 2011/12/01 23:26:13
created_gmt: 2011/12/02 04:26:13
comment_status: open
slug: add-a-key-to-all-items-on-a-mongodb-collection

<!--Again, I am posting this because it took me more than expected to find this easy answer. <a href="http://stackoverflow.com/questions/5587677/mongodb-unconditional-updates">I found it on StackOverflow</a>, but I will repost and explain here. -->

Again, I am posting this because it took me more than expected to find this easy answer. [I found it on StackOverflow](http://stackoverflow.com/questions/5587677/mongodb-unconditional-updates), but I will repost and explain here. 

Since [Mongo](http://www.mongodb.org/) is a schemaless database, there is no "`ALTER TABLE`", so what you need to do is update all the items. 

The [MongoDB documentation on Updates](http://www.mongodb.org/display/DOCS/Updating) is not very clear on how to do this. And the [SQL to Mongo mapping ](http://www.mongodb.org/display/DOCS/SQL+to+Mongo+Mapping+Chart)doesn't explain this either. 

So, here's how you do it. You perform an `update` with empty criteria 
    
    
    
    
    
    
    db.collection.update( criteria, objNew, upsert, multi )
    
    
    
    
    

We want to update all the elements, so we use empty criteria 
    
    
    {}

We want to add an attribute, so we will $set the key, it will be in the form of a document to be "merged" with each item. 
    
    
    {'$set': {new_key:value}}

We don't want upsert. So we set that to `False`, if we set it to true, the update call will add an item to the collection containing the value we wanted to set and nothing more, which is not what we want. 

For multi, we will say `True`, because we want the update to happen on all the collection item's and not just the first one. 
    
    
    
    
    
    
    db.collection.update( {}, {'$set': {new_key:value}}, false, true)