How to push value with for loop in MongoDB?

To push values with a for loop in MongoDB, use the save() method inside a for loop to insert multiple documents iteratively. This approach is useful when you need to create many similar documents programmatically.

Syntax

for(var i = start; i 

Example

Create 6 documents using a for loop ?

for(var v = 1; v 

WriteResult({ "nInserted" : 1 })

Verify the Results

Display all documents from the collection using find() ?

db.demo739.find();
{ "_id" : ObjectId("5ead6e7857bb72a10bcf0666"), "Name" : "Chris", "SubjectName" : "MongoDB" }
{ "_id" : ObjectId("5ead6e7857bb72a10bcf0667"), "Name" : "Chris", "SubjectName" : "MongoDB" }
{ "_id" : ObjectId("5ead6e7857bb72a10bcf0668"), "Name" : "Chris", "SubjectName" : "MongoDB" }
{ "_id" : ObjectId("5ead6e7857bb72a10bcf0669"), "Name" : "Chris", "SubjectName" : "MongoDB" }
{ "_id" : ObjectId("5ead6e7857bb72a10bcf066a"), "Name" : "Chris", "SubjectName" : "MongoDB" }
{ "_id" : ObjectId("5ead6e7857bb72a10bcf066b"), "Name" : "Chris", "SubjectName" : "MongoDB" }

Key Points

  • Each iteration of the loop creates a new document with a unique _id.
  • The save() method automatically generates ObjectId values for each document.
  • Variables within the loop can be used to create dynamic field values.

Conclusion

Using for loops with save() provides an efficient way to insert multiple documents programmatically. This method is particularly useful for testing, data seeding, or bulk document creation scenarios.

Updated on: 2026-03-15T03:53:42+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements