Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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; iExample
Create 6 documents using a for loop ?
for(var v = 1; vWriteResult({ "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.
Advertisements
