• Home
  • Testing
  • SAP
  • Web
  • Must Learn!
  • Big Data
  • Live Projects
  • AI
  • Blog

The "insert" command can also be used to insert multiple documents into a collection at one time. The below code example can be used to insert multiple documents at a time.

The following example shows how this can be done,

Step 1) Create a JavaScript variable called myEmployee to hold the array of documents

Step 2) Add the required documents with the Field Name and values to the variable

Step 3) Use the insert command to insert the array of documents into the collection

var myEmployee=
	[
	
		{
			"Employeeid" : 1,
			"EmployeeName" : "Smith"
		},
		{
			"Employeeid"   : 2,
			"EmployeeName" : "Mohan"
		},
		{
			"Employeeid"   : 3,
			"EmployeeName" : "Joe"
		},

	];

	db.Employee.insert(myEmployee);

If the command is executed successfully, the following Output will be shown

Add MongoDB Array using insert()

The output shows that those 3 documents were added to the collection.

Printing in JSON format

JSON is a format called JavaScript Object Notation, and is just a way to store information in an organized, easy-to-read manner. In our further examples, we are going to use the JSON print functionality to see the output in a better format.

Let's look at an example of printing in JSON format

db.Employee.find().forEach(printjson)

Code Explanation:

  1. The first change is to append the function called for Each() to the find() function. What this does is that it makes sure to explicitly go through each document in the collection. In this way, you have more control of what you can do with each of the documents in the collection.
  2. The second change is to put the printjson command to the forEach statement. This will cause each document in the collection to be displayed in JSON format.

If the command is executed successfully, the following Output will be shown

Output:

Add MongoDB Array using insert()

The output clearly shows that all of the documents are printed in JSON style.

 

YOU MIGHT LIKE:
MongoDB

MongoDB Cursor

When the db.collection.find () function is used to search for documents in the collection, the...