Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new field to every document in a MongoDB collection

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?

like image 899
itsme Avatar asked Oct 10 '11 14:10

itsme


People also ask

How can I insert a new field in an existing MongoDB collection document?

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 .

How do I add multiple values to a collection in MongoDB?

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.


2 Answers

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})  
like image 130
RameshVel Avatar answered Nov 08 '22 10:11

RameshVel


Since MongoDB version 3.2 you can use updateMany():

> db.yourCollection.updateMany({}, {$set:{"someField": "someValue"}}) 
like image 43
qwertz Avatar answered Nov 08 '22 09:11

qwertz