Learning MongoDB

0% completed

Previous
Next
Insert Operations

Insert operations are the first step in interacting with a MongoDB database. They allow you to add new documents to a collection, making them essential for building and populating your database.

MongoDB provides three methods for inserting documents:

  • insert()
  • insertOne()
  • insertMany().

Each method has its own use cases and advantages. This lesson will cover these methods in detail, explaining how to use them effectively to insert data into your MongoDB collections.

insert() Method

The insert() method is used to add one or more documents to a collection. It was the primary method for inserting documents in MongoDB before version 3.2. While it can still be used, it has been superseded by the more specific insertOne() and insertMany() methods. The insert() method is flexible but has limitations compared to the newer methods.

The insert() method can accept a single document or an array of documents. When a single document is inserted, it behaves similarly to insertOne(). When an array of documents is inserted, it functions like insertMany(). This flexibility makes it a versatile but less commonly used method in modern MongoDB applications.

Syntax

db.collection.insert( <document or array of documents>, <options> )
  • document or array of documents: The document(s) to insert into the collection.
  • options (optional): An object specifying the options for the insert operation.

Examples

  1. Inserting a Single Document
db.users.insert({ name: "John Doe", age: 30, email: "john.doe@example.com" })

This command inserts a single document into the users collection. The document contains fields for name, age, and email.

  1. Inserting Multiple Documents
db.users.insert([ { name: "Alice", age: 25, email: "alice@example.com" }, { name: "Bob", age: 30, email: "bob@example.com" } ])

This command inserts an array of documents into the users collection. Each document represents a user with fields for name, age, and email.

  1. Handling Errors
try { db.users.insert([ { _id: 1, name: "Charlie", age: 35 }, { _id: 1, name: "Dave", age: 40 } ]) } catch (e) { print(e) }

This command attempts to insert two documents with the same _id. MongoDB will throw a duplicate key error. The try and catch block is used to handle the error and print the error message.

insertOne() Method

The insertOne() method is used to insert a single document into a collection. It is part of MongoDB's new CRUD API introduced in version 3.2, which provides more specific and clear methods for database operations. insertOne() is the preferred method for inserting a single document due to its simplicity and explicitness.

Syntax

db.collection.insertOne( <document>, <options> )
  • document: The document to insert into the collection.
  • options (optional): An object specifying the options for the insert operation.

Examples

  1. Basic Insertion

The insertOne() method takes a single document as an argument and inserts it into the specified collection. If the document does not have an _id field, MongoDB automatically generates a unique _id for it. This method returns a result object that includes the _id of the inserted document.

db.users.insertOne({ name: "John Doe", age: 30, email: "john.doe@example.com" })

This command inserts a single document into the users collection with name, age, and email fields.

  1. Insertion with a Specified _id
db.users.insertOne({ _id: ObjectId("507f1f77bcf86cd799439011"), name: "Alice", age: 25, email: "alice@example.com" })

This command inserts a document with a specified _id. If the _id is unique, the document is inserted successfully.

  1. Handling Result
let result = db.users.insertOne({ name: "Bob", age: 30, email: "bob@example.com" }) print("Inserted document ID: " + result.insertedId)

This command inserts a document and stores the result in the result variable. The inserted document's _id is then printed.

insertMany() Method

The insertMany() method is used to insert multiple documents into a collection at once. This method is efficient for bulk insertions and is part of MongoDB's new CRUD API introduced in version 3.2. insertMany() provides more control and error handling capabilities compared to the older insert() method.

Syntax

db.collection.insertMany( <array of documents>, <options> )
  • array of documents: The documents to insert into the collection.
  • options (optional): An object specifying the options for the insert operation, such as:
    • ordered: If true, MongoDB inserts the documents in the order provided and stops on the first error. If false, MongoDB attempts to insert all the documents regardless of errors.
    • writeConcern: Specifies the write concern for the operation.

Examples

  1. Basic Insertion

The insertMany() method takes an array of documents as an argument and inserts them into the specified collection. If any document does not have an _id field, MongoDB automatically generates a unique _id for it. This method returns a result object that includes the _id values of all inserted documents. You can also specify options such as ordered to control the insertion behavior in case of errors.

db.users.insertMany([ { name: "Alice", age: 25, email: "alice@example.com" }, { name: "Bob", age: 30, email: "bob@example.com" }, { name: "Charlie", age: 35, email: "charlie@example.com" } ])

This command inserts an array of documents into the users collection. Each document represents a user with name, age, and email fields.

  1. Handling Result
let result = db.users.insertMany([ { name: "Dave", age: 40, email: "dave@example.com" }, { name: "Eve", age: 45, email: "eve@example.com" } ]) print("Inserted document IDs: " + result.insertedIds)

This command inserts multiple documents and stores the result in the result variable. The _id values of the inserted documents are then printed.

  1. Ordered Insertion
db.users.insertMany([ { name: "Frank", age: 50, email: "frank@example.com" }, { _id: 1, name: "Grace", age: 55, email: "grace@example.com" }, // This will cause a duplicate key error { name: "Heidi", age: 60, email: "heidi@example.com" } ], { ordered: false })

By setting the ordered option to false, MongoDB will continue to insert the remaining documents even if an error occurs with one of the documents. In this example, the second document causes a duplicate key error, but the third document is still inserted.

  1. Error Handling
try { db.users.insertMany([ { _id: 1, name: "Ivan", age: 65, email: "ivan@example.com" }, { _id: 1, name: "Judy", age: 70, email: "judy@example.com" } // This will cause a duplicate key error ]) } catch (e) { print(e) }

This command attempts to insert multiple documents with the same _id, resulting in an error. The try and catch block captures and prints the error.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next