Jj Del Carpio

Jj's web stream

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. I found it on StackOverflow, but I will repost and explain here.

Since Mongo 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 is not very clear on how to do this. And the SQL to Mongo mapping 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)
Jj Avatar of Jj

Reply or react to this post via Webmentions