How can I add a new field to every document in an existent collection?
I know how to update an existing document's field but not how to add a new field to every document in a collection. How can I do this in the mongo
shell?
To add field or fields to embedded documents (including documents in arrays) use the dot notation. See example. To add an element to an existing array field with $addFields , use with $concatArrays .
You are allowed to insert multiple documents in the collection by using db. collection. insertMany() method. insertMany() is a mongo shell method, which can insert multiple documents.
Same as the updating existing collection field, $set
will add a new fields if the specified field does not exist.
Check out this example:
> db.foo.find() > db.foo.insert({"test":"a"}) > db.foo.find() { "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" } > item = db.foo.findOne() { "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" } > db.foo.update({"_id" :ObjectId("4e93037bbf6f1dd3a0a9541a") },{$set : {"new_field":1}}) > db.foo.find() { "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "new_field" : 1, "test" : "a" }
EDIT:
In case you want to add a new_field to all your collection, you have to use empty selector, and set multi flag to true (last param) to update all the documents
db.your_collection.update( {}, { $set: {"new_field": 1} }, false, true )
EDIT:
In the above example last 2 fields false, true
specifies the upsert
and multi
flags.
Upsert: If set to true, creates a new document when no document matches the query criteria.
Multi: If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document.
This is for Mongo versions
prior to 2.2
. For latest versions the query is changed a bit
db.your_collection.update({}, {$set : {"new_field":1}}, {upsert:false, multi:true})
Since MongoDB version 3.2 you can use updateMany():
> db.yourCollection.updateMany({}, {$set:{"someField": "someValue"}})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With