Mass insertion in MongoDB


For mass insertion, use the concept of insertMany() in MongoDB. The insertMany() inserts multiple documents into a collection.

Let us create a collection with documents −

> db.demo729.insertMany( [
...    { BankName:"HDFC Bank",cardType:"Credit","CustomerName":[{Name:"Chris",Age:25}]},
...    { BankName:"ICICI Bank",cardType:"Debit","CustomerName":[{Name:"Bob",Age:22}]},
...    { BankName:"Kotak Bank",cardType:"Debit","CustomerName":[{Name:"David",Age:23}]}
... ] );
{
   "acknowledged" : true,
   "insertedIds" : [
      ObjectId("5eac510d56e85a39df5f6333"),
      ObjectId("5eac510d56e85a39df5f6334"),
      ObjectId("5eac510d56e85a39df5f6335")
   ]
}

Display all documents from a collection with the help of find() method −

> db.demo729.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5eac510d56e85a39df5f6333"),
   "BankName" : "HDFC Bank",
   "cardType" : "Credit",
   "CustomerName" : [
      {
         "Name" : "Chris",
         "Age" : 25
      }
   ]
}
{
   "_id" : ObjectId("5eac510d56e85a39df5f6334"),
   "BankName" : "ICICI Bank",
   "cardType" : "Debit",
   "CustomerName" : [
      {
         "Name" : "Bob",
         "Age" : 22
      }
   ]
}
{
   "_id" : ObjectId("5eac510d56e85a39df5f6335"),
   "BankName" : "Kotak Bank",
   "cardType" : "Debit",
   "CustomerName" : [
      {
         "Name" : "David",
         "Age" : 23
      }
   ]
}

Updated on: 15-May-2020

61 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements