0% completed
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.
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.
db.collection.insert( <document or array of documents>, <options> )
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
.
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
.
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.
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.
db.collection.insertOne( <document>, <options> )
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.
_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.
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.
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.
db.collection.insertMany( <array of documents>, <options> )
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.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.
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.
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.
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.
.....
.....
.....