ChatGPT解决这个技术问题 Extra ChatGPT

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?


n
ndmeiri

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}) 

Is it possible to create without value
db.your_collection.update({}, {$set : {"new_field":null}}, {upsert:false, multi:true})
what if I want to create an empty array?
@PrashantPokhriyal db.your_collection.update({}, {$set : {"new_field":[]}}, {upsert:false, multi:true})
What if you want to create the new field with the value assigned dynamically? For example, I would like to have new_field to be an int equal to the length of the string in test field.
q
qwertz

Since MongoDB version 3.2 you can use updateMany():

> db.yourCollection.updateMany({}, {$set:{"someField": "someValue"}})

I think updateMany is more readable
L
LineDrop

To clarify, the syntax is as follows for MongoDB version 4.0.x:

db.collection.update({},{$set: {"new_field*":1}},false,true)

Here is a working example adding a published field to the articles collection and setting the field's value to true:

db.articles.update({},{$set: {"published":true}},false,true)

Using updateMany will be more right
K
KRRISH96
db.collection.updateMany({}, {$set: {"fieldName": ""}})

updateMany requires a matching condition for each document, since we are passing {} it is always true. And the second argument uses $set operator to add the required field in each document.


While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
A
Alex Jolig

Pymongo 3.9+

update() is now deprecated and you should use replace_one(), update_one(), or update_many() instead.

In my case I used update_many() and it solved my issue:

db.your_collection.update_many({}, {"$set": {"new_field": "value"}}, upsert=False, array_filters=None)

Is it "update_many" or "updateMany" ?
@Abdulhakim it's update_many
Hey guys, can I add a new field to each document from an array which is having a different value for each document.
@JAbr I don't know the answer, but better open a new question, because unless they're follow-ups to the original question, people don't usually answer new questions in the comments.
E
Edgar Olivar

if you are using mongoose try this,after mongoose connection

async ()=> await Mongoose.model("collectionName").updateMany({}, {$set: {newField: value}})

hey @Edgar can you explain this in more detail by taking an example, and can you share documents , where you have found this?
hi @RohanDevaki , yes, mongoosejs.com/docs/models.html in "Updating" sections, in that page you see the example: "Tank" model = Mongoose.model("Tank") and the updateMany function you can find in docs.mongodb.com/manual/reference/method/…
but while setting a new filed, you also need to mention the type of the new field right, where did you mention the type, and you have to add, whether it is required or not, how will you add these?
K
KushalSeth

The answers above does't cover this scenario. I was looking for the similar query but want to add fields to few documents based on condition.

So, we can use first variable of updateMany to update fields only in few documents.

Example: I want to add a nullable field isDeprecated? to all those Users whose userType is Employer and has country "AAA".

db.users.updateMany({"userType": "Employer", "country": "AAA"}, {"$set": { "isDeprecated?": true }})  

This answer will be helpful in those scenarios as well, where we have to find the collection and then update. This can we done in single query like mentioned.