MongoDB Array of Objects using insert() with Example

⚡ Smart Summary

MongoDB Array of Objects using insert() shows how to add several documents to a collection in one operation. It stores an array of employee records, embeds arrays inside a document, and displays results neatly using the JSON print function.

  • 📥 Bulk Insert: The insert() method adds an array of documents to a collection in a single, efficient operation.
  • 🧾 Document Model: Each document is a set of field-and-value pairs, and MongoDB adds a unique _id automatically.
  • 🗂️ Embedded Arrays: An array can also live as a field inside one document, keeping related values together.
  • 🔁 Modern Methods: insertOne() and insertMany() are the current, clearer replacements for the legacy insert() method.
  • 🖨️ Readable Output: The forEach(printjson) command prints every document in a clean, easy-to-read JSON format.

What is the insert() Method in MongoDB?

The insert() method in MongoDB adds one or more documents to a collection. A document is a set of field-and-value pairs stored in BSON, a binary form of JSON. When you pass a single document, insert() stores that one record; when you pass an array of documents, it stores all of them in a single operation, which is faster than inserting them one by one.

The method is run against a specific collection using the pattern db.collection.insert(). If the target collection does not yet exist, MongoDB creates it automatically during the first insert. Each document also receives a unique _id field if you do not supply one, so every record can be identified later.

While insert() still works, newer MongoDB versions provide insertOne() and insertMany() as clearer replacements. The examples below use insert() to add an array of employee documents and then display the results in a readable JSON format.

Adding an Array of Documents

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

MongoDB Array of Objects using insert()

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

How to Insert an Array Inside a Document

Besides inserting an array of separate documents, MongoDB lets you store an array as a field inside a single document. This is useful when one record naturally contains a list of values, such as an employee who has several skills or a student enrolled in multiple courses. Because MongoDB uses a flexible document model, the array lives directly inside the object rather than in a separate table, which keeps related data together.

The following example inserts one employee document that contains an array field called Skills:

db.Employee.insert(
   {
      "Employeeid" : 4,
      "EmployeeName" : "Alan",
      "Skills" : [ "MongoDB", "Node.js", "Express" ]
   }
);

The parts of this document work as follows:

  • Employeeid and EmployeeName are ordinary field-and-value pairs.
  • Skills is an array field that holds three string values inside square brackets.
  • The entire document, including the embedded array, is stored in a single insert operation.

After adding the record, you can confirm the embedded array with a find query that prints the result in JSON:

db.Employee.find( { "Employeeid" : 4 } ).forEach(printjson)

The output shows the Skills array nested inside the employee document. Later, you can add new values to the array with the $push operator, or read a single element by its index position. Storing connected values this way keeps each document self-contained, reduces the need for joins across collections, and makes the data easier to read and maintain.

insert() vs insertOne() vs insertMany()

MongoDB provides three related methods for adding data. The table below compares them so you can choose the right one:

Method Purpose Example
insert() Legacy method that adds a single document or an array of documents. It still works but is deprecated in newer drivers. db.Employee.insert(myEmployee)
insertOne() Adds exactly one document and returns its inserted _id. Preferred for single records. db.Employee.insertOne({ … })
insertMany() Adds an array of documents in one call and returns all inserted _ids. Preferred for bulk inserts. db.Employee.insertMany([ { … }, { … } ])

For new projects, use insertOne() and insertMany() because they give clearer intent and better error reporting. The insert() method remains available mainly for backward compatibility with older tutorials and scripts.

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 forEach() 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:

Printing in JSON Format

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

FAQs

Yes. Passing an array of documents to insert() adds them all in one operation. This bulk insert is faster than calling insert() separately for each document, though insertMany() is now the preferred method.

Yes. If a document does not include an _id field, MongoDB automatically generates a unique ObjectId for it during insertion, so every stored record can be identified and retrieved later.

By default, MongoDB performs an ordered insert. It adds documents in the given order and stops at the first error, leaving the remaining documents uninserted. Setting ordered to false continues past errors.

Yes. AI tools can turn a plain-language description of your data into insertOne() or insertMany() statements, including embedded arrays. Always review the generated fields and data types before running them on a database.

AI can suggest whether to embed arrays inside a document or reference separate collections, based on your query patterns. This helps beginners model data efficiently while avoiding unnecessary duplication or overly deep nesting.

Summarize this post with: