• Post author:
  • Post category:MongoDB
  • Post last modified:May 9, 2024
  • Reading time:14 mins read
You are currently viewing MongoDB insertOne() & insertMany() Documents

To insert single or multiple documents into a MongoDB collection, you can use either insertOne() or insertMany() methods respectively. Alternatively, you can also use the insert() method to insert single and multiple documents but, this has been deprecated in mongosh shell.

Advertisements

Inserting data into a collection is one of the core activities in MongoDB. This article will explore how to insert data into MongoDB using the MongoDB shell. Note that the insert() method has been deprecated with the alternative method in mongosh shell.  The insertOne() and insertMany() methods are some of the alternate approaches.

1. MongoDB insertOne() – Insert a single document

In MongoDB, the insertOne() method is used to insert a single document (a record) into a collection. Let’s see the syntax of this method and an example.

1.1 Syntax of insertOne()

Following is the syntax of the insertOne().


# insertOne() Method
db.collection.insertOne(
   <document>,
   {
      writeConcern: <document>,
      bypassDocumentValidation: <boolean>
   }
)

Here,

  • db.collection: Replace collection with the name of the MongoDB collection where you want to insert the document. You need to have an active MongoDB connection and select the database before running this command.
  • <document>: This is a JavaScript object representing the document you want to insert into the collection. It should be in the form of key-value pairs, where keys are the field names, and values are the data you want to store.
  • writeConcern (optional): This is an optional parameter that allows you to specify the level of acknowledgment for the write operation. You can set options like { w: 1 } for acknowledgment from the primary node or { w: "majority" } for acknowledgment from the majority of nodes in a replica set.
  • bypassDocumentValidation (optional): This is an optional boolean parameter that, when set to true, allows you to bypass document validation rules defined in the schema.

1.2 Example of insertOne()

To insert a document into a MongoDB database using the MongoDB Shell, we typically run the insertOne() function on a MongoDB collection object. Here is an example.


# insertOne() Method
db.student.insertOne({name: "David",age: 25, marks: 90})

In the above example, the insertOne() function is deployed to insert a document with the fields’ name, age, and marks into the student collection. The given fields are specified with the different values and different data types.

The output is generated below upon execution of the insertOne() method command. Additionally, the _id field, which uniquely identifies the document, is automatically generated by MongoDB unless explicitly provided.

Insertone document MongoDB

More details about this method can be found here.

1.3 Insert the documents by _id field

As in the aforementioned examples, we have inserted the documents in the collection without specifying the _id field. However, the _id value can be explicitly specified within the document as follows.


# Insert documents by _id field
db.student.insertOne({_id: 201, name: "Bella", marks: 95})

Here, we have tried to insert a document into the student collection with a specific _id value of 201 using the insertOne() method because it’s a single document. Also, we have inserted two other fields in the same document, which include the name field being set to Bella and the marks field being set to 95.

The output yielded showed the inserted document with the particular id value.

Insert document MongoDB

2. MongoDB insertMany() – Insert multiple documents

In MongoDB, the insertMany() method is used to insert multiple documents (records) into a collection in a single operation. It is more efficient than inserting documents one by one using insertOne() for each document when you need to insert multiple documents simultaneously.

2.1 Syntax of insertMany()

Following is the syntax of the insertMany() method.


# Syntax of insertMany() method
db.collection.insertMany(
   <documents>,
   {
      writeConcern: <document>,
      ordered: <boolean>
   }
)

Here,

  • db.collection: Replace collection with the name of the MongoDB collection where you want to insert the documents.
  • <documents>: This is an array of JavaScript objects representing the documents you want to insert into the collection. Each object in the array represents a document.
  • writeConcern (optional): This is an optional parameter that allows you to specify the level of acknowledgment for the write operation. You can set options like { w: 1 } for acknowledgment from the primary node or { w: "majority" } for acknowledgment from the majority of nodes in a replica set.
  • ordered (optional): This is an optional boolean parameter that determines whether the inserts should be performed in order. If set to true (the default), MongoDB will insert the documents in the order they appear in the array, and if any document fails to insert, the remaining documents will not be processed. If set to false, MongoDB will attempt to insert all documents and report any errors after the operation is complete.

2.2 Example of insertMany()

Here’s an example of using insertMany() to insert multiple documents into a MongoDB collection from the mongosh shell. To insert multiple documents into the MongoDB collection, the insertMany() method should be used.  We can execute the following command, which shows the insertMany() method structure.


# Usage of insertMany() method
db.student.insertMany([{name: "Billy", age: 21, marks: 85}, 
                   {name: "Alaric", age: 24, marks: 75},
                   {name: "Henna", age: 22, marks: 80}])

The prior command is deployed with the insertMany() method to insert the provided documents into the student collection at once. Each document consists of the fields name, age, and marks with their respective values.

The command created the collection of these multiple documents and returned the unique _id values for each document in the output.

InsertMany in MongoDB

3. Insert array document using insertMany()

Additionally, array-based documents can be inserted into the collection using the insertOne() or either with the insertMany() method. Here, the single document which contains the array object is inserted via the insertOne() method.


# Insert array document
var bulk = db.student.initializeUnorderedBulkOp();  
bulk.insert(  
   {  
     degree: "Computer Science",    
     name: "Harry",  
     age: 26  
   }
);  
bulk.execute();  

The insertOne() method is set up with the document, which contains the field _id, info, and courses. Consider the info field, which is an array of objects. Each object represents a key-value pair, with the first object having the key name and value Alice, and the second object having the key age and value 29. Next, the course field is an array of strings containing the courses Python and MongoDB.

Thus, the document of array objects has been inserted into the provided collection. 

4. Insert the document using the bulk method

Moreover, the Bulk Write Operations API in MongoDB can also be utilized to insert a single document unordered. The operations are performed as a batch for improved efficiency. Here’s an illustration of the bulk method to insert the document.


# Usage of bulk method
db.student.insertOne({
    _id : 234,
    info : [{"name": "Alice"},{"age": 29}],
    courses : ["Python", "MongoDB"]
});

First, we initialize a new unordered bulk operation for the student collection and assign it to the bulk variable. We then added an insert operation to the bulk operation. It specifies a document with the fields degree set to Computer Science, name set to Harry, and age set to 26. Lastly, we called the execute() method to execute the bulk operation.

Hence, the output displayed the insertion of a single document.

Insert in MongoDB

5. Conclusion

In conclusion, we have reviewed the fundamentals of using the MongoDB shell to insert data into MongoDB. Remember that MongoDB is an incredible tool for managing various data since its flexibility enables us to input documents with different structures into the same collection.

To insert a document (record) into a MongoDB collection, you can use the insertOne or insertMany() methods, depending on whether you want to insert one document or multiple documents at a time.