Solve this problem

I inserted 1000 data using for loop.

for example :

for( i=1;i<=1000;i++ ){
     db.w1000.insertOne({"name":"ajay"+i})
}

Now what if I want to insert a new column with the same collection like

"name":"ajay1"
"age":21

"name":"ajay2"
"age":22
And 
So
On
. 
. 

what we do?

Hi :wave: @Ajay_Moladiya,

Welcome to the MongoDB Community forums :sparkles:

I assume you want to add a new field named “age” to the existing collection and have its value automatically increment starting from 21.

If yes, you can use db.collection.updateMany() and $set:

for (i = 1; i <= 1000; i++) { 
db.w1000.updateMany( 
      { name: "ajay" + i }, { $set: { age: i + 20 } }
)}

It will add an additional field age to your document, and the collection will appear as follows:

{
  "_id": ObjectID("643179077d77041fb1eaea8a"),
  "name": "ajay1",
  "age": 21
},
{
  "_id": ObjectID("643179077d77041fb1eaea8b"),
  "name": "ajay2",
  "age": 22
}
... so on

I hope it answers your question. Let us know if you have any further questions.

Regards,
Kushagra

1 Like

Okay sir , Thank you !!