Insert in MongoDB
Inserting Data in MongoDB
In MongoDB, inserting data involves adding documents to collections. MongoDB provides several methods for inserting data, including inserting a single document, multiple documents, or even a document with more complex structures.
Let’s walk through the different ways to insert data in MongoDB.
1. Inserting a Single Document
To insert a single document into a collection, you can use the insertOne() method. This method inserts one document and returns a result that contains information about the operation, including the inserted document's _id.
Syntax:
db.{ "acknowledged": true: ObjectId("60d21b4667d0d8992e610c85")}
- The
insertedIdis the automatically generated_idof the inserted document.
2. Inserting Multiple Documents
If you need to insert multiple documents at once, you can use the insertMany() method. This method allows you to insert an array of documents in one operation, and MongoDB will automatically generate an _id for each document if not specified.
Syntax:
db.collection.insertMany([document1, document2, ...])
Example:
db.users.insertMany([ { name: "Bob", age: 25, email: "bob@example.com", isActive: false }, { name: "Charlie", age: 35, email: "charlie@example.com", isActive: true }, { name: "Diana", age: 28, email: "diana@example.com", isActive: true }])
Result:
{ "acknowledged": true, "insertedIds": { "0": ObjectId("60d21b4667d0d8992e610c86"), "1": ObjectId("60d21b4667d0d8992e610c87"), "2": ObjectId("60d21b4667d0d8992e610c88") }}
- The
insertedIdsfield contains the_idvalues of the documents that were inserted.
3. Inserting a Document with a Custom _id
By default, MongoDB automatically generates a unique _id for each document if one is not provided. However, you can manually specify the _id field if you need to have control over it.
Example:
db.{ "acknowledged": true: "user123"}
- MongoDB allows you to use strings or other types for the
_idfield, but it is recommended to useObjectIdfor consistency and performance unless there’s a specific requirement for custom IDs.
4. Inserting Data with an Embedded Document
MongoDB allows you to insert complex documents, including those with embedded documents or arrays.
Example:
db.orders.insertOne({ orderId: 12345, customer: { name: "Alice", email: "alice@example.com" }, items: [ { productId: 1, quantity: 2, price: 50 }, { productId: 2, quantity: 1, price: 30 } ], totalAmount: 130})
- This document has an embedded
customerdocument and an array ofitems.
Result:
{ "acknowledged": true, "insertedId": ObjectId("60d21b4667d0d8992e610c89")}
5. Handling Errors During Insert
If you try to insert a document with a duplicate _id (in the case where you're manually specifying _id), MongoDB will throw an error because the _id field must be unique within a collection.
Example:
db.users.insertOne({ _id: "user123", // Same _id as before name: "Eve", age: 40, email: "eve@example.com", isActive: true})
Error:
{ "error": "E11000 duplicate key error collection: test.users index: _id_ dup key: { : \"user123\" }"}
- MongoDB throws a duplicate key error because the
_idvalue"user123"already exists in the collection.
6. Insert with Validation (Schema Validation)
MongoDB offers schema validation to ensure that inserted documents follow a specific structure. You can define validation rules using MongoDB's validator feature during collection creation or update.
For example, if you want to create a users collection where the age field is required and should be an integer:
Example:
db.createCollection("users", { validator: { $jsonSchema: { bsonType: "object", required: ["name", "age", "email"], properties: { name: { bsonType: "string" }, age: { bsonType: "int" }, email: { bsonType: "string" } } } }})
Then, if you try to insert a document without the required fields or with an invalid type, MongoDB will reject the insert:
Example:
db.users.insertOne({ name: "Frank", email: "frank@example.com" }) // Missing 'age'
Error:
{ "error": "Document failed validation"}
7. Insert Data from Other Sources (Bulk Insert)
If you need to insert a large amount of data from an external source (such as a CSV or JSON file), you can use MongoDB tools like mongoimport for batch import or the bulkWrite() method in MongoDB to insert many documents programmatically.
Example with bulkWrite():
const bulk = db.users.initializeUnorderedBulkOp();bulk.insert({ name: "Grace", age: 28, email: "grace@example.com" });bulk.insert({ name: "Henry", age: 32, email: "henry@example.com" });bulk.execute();
- This approach is more efficient than inserting documents one by one when dealing with large volumes of data.
Conclusion
- InsertOne: Use this method for inserting a single document into a collection.
- InsertMany: Use this method for inserting multiple documents in one go.
- Custom
_id: You can provide a custom value for the_idfield if needed. - Embedded Documents: MongoDB allows you to insert documents with nested structures like arrays and objects.
- Schema Validation: You can define rules to enforce the structure and types of documents inserted into a collection.
Inserting data into MongoDB is straightforward and can handle a wide range of data types and structures, making it flexible and scalable for different use cases.