Use insertMany() to insert multiple documents into a collection. With that, to update performance you can use ensureIndex().
Let us create a collection with documents and insert multiple documents −
> db.demo325.insertMany( [ ... { _id: 101, Name: "Chris", Age: 23 }, ... { _id: 102, Name: "David", Age: 24 }, ... { _id: 103, Name: "Bob", Age: 22 } ... ] ); { "acknowledged" : true, "insertedIds" : [ 101, 102, 103 ] }
Display all documents from a collection with the help of find() method −
> db.demo325.find().pretty();
This will produce the following output −
{ "_id" : 101, "Name" : "Chris", "Age" : 23 } { "_id" : 102, "Name" : "David", "Age" : 24 } { "_id" : 103, "Name" : "Bob", "Age" : 22 }
Using ensureIndex() −
> db.demo325.ensureIndex({Name:1});
This will produce the following output −
{ "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }