Adding key in all collection object is bit tricky in mongoDB as there is nothing like alter table
db.collection.update( criteria, ourobj, upsert, multi )
- criteria is used to select objects which will be updated. e.g {“name”:”testName”}
- ourobject is the document which will be appended or overwrite fields of object found by criteria
- upsert stand for update or insert true/false
- multi will the query effect multiple object true/false
In our case since we want to add a single key value to all objects existing in our database we will have
1.criteria : {} empty object to act like *
2. ourobject :{$set:{“our_key”:”test_value”}} $set is for appending
3.upsert: false since we want to update existing objects only we will set it to false
4. multi: true since we have to update more then one object so mutli is set to true
then our query becomes
db.collection.update( {}, {'$set': {our_key:test_value}}, false, true)