MongoDB - Insert Document
MongoDB - Inserting Documents
Section titled “MongoDB - Inserting Documents”This chapter covers how to insert documents into a MongoDB collection using modern, recommended methods. We will focus on the insertOne() and insertMany() methods, which provide clear and explicit intent for your database operations.
Modern Insertion Methods: insertOne() and insertMany()
Section titled “Modern Insertion Methods: insertOne() and insertMany()”In modern MongoDB versions, the primary methods for adding new documents are insertOne() for adding a single document and insertMany() for adding multiple documents in a single operation. These methods are preferred over the legacy insert() method for their explicit nature and clearer return values.
**Deprecation Notice:** The older `db.collection.insert()` and `db.collection.save()` methods are deprecated. While they may still work in some versions for backward compatibility, you should always use `insertOne()`, `insertMany()`, or `replaceOne()`/`updateOne()` in new applications to ensure clarity and future compatibility.The insertOne() Method
Section titled “The insertOne() Method”Use the insertOne() method to insert a single document into a collection. If the collection does not currently exist, MongoDB creates it upon the first insert.
Syntax
Section titled “Syntax”db.collectionName.insertOne( <document>, { writeConcern: <document> })The writeConcern option specifies the level of acknowledgment requested from MongoDB for write operations. It’s an advanced topic, and for most use cases, the default is sufficient.
Example: Inserting a Single User
Section titled “Example: Inserting a Single User”Let’s insert a document into a users collection. If we don’t provide an _id field, MongoDB will automatically generate a unique ObjectId for it.
> db.users.insertOne({... name: "Alice Johnson",... email: "alice.j@example.com",... roles: ["user", "editor"],... signupDate: new Date(),... profile: {... age: 28,... city: "New York"... }... }){ acknowledged: true, insertedId: ObjectId("64a5f1e1a2b3c4d5e6f7a8b9")}Understanding the _id Field
Section titled “Understanding the _id Field”The _id field is the primary key for a collection and must be unique for every document. MongoDB automatically generates a unique 12-byte ObjectId if you don’t specify one. The structure is:
_id: ObjectId( [4-byte timestamp], [5-byte random value], [3-byte incrementing counter])The insertMany() Method
Section titled “The insertMany() Method”To insert multiple documents at once, use the insertMany() method. This is far more efficient than calling insertOne() in a loop because it requires only a single round trip to the database.
Syntax
Section titled “Syntax”db.collectionName.insertMany( [ <document1>, <document2>, ... ], { writeConcern: <document>, ordered: <boolean> })The ordered option (default true) specifies whether MongoDB should perform an ordered or unordered insert. In an ordered insert, if an error occurs, MongoDB stops processing the remaining documents. In an unordered insert, it attempts to insert all documents, regardless of errors.
Example: Inserting Multiple Products
Section titled “Example: Inserting Multiple Products”> db.products.insertMany([... {... name: "Laptop Pro 15-inch",... category: "Electronics",... price: 1299.99,... tags: ["computer", "pro", "work"],... stock: 50... },... {... name: "Wireless Mouse",... category: "Accessories",... price: 49.99,... tags: ["input", "ergonomic"],... stock: 200... },... {... _id: "custom_monitor_id_123", // Providing a custom _id... name: "4K UHD Monitor",... category: "Electronics",... price: 399.00,... tags: ["display", "4k"],... stock: 75... }... ]){ acknowledged: true, insertedIds: [ ObjectId("64a5f2e2a2b3c4d5e6f7a8ba"), ObjectId("64a5f2e2a2b3c4d5e6f7a8bb"), 'custom_monitor_id_123' ]}Best Practices and Common Errors
Section titled “Best Practices and Common Errors”Best Practices
Section titled “Best Practices”- Use Bulk Operations: Always prefer
insertMany()over multipleinsertOne()calls for inserting more than one document to reduce network overhead. - Handle Errors: When using the MongoDB drivers in an application (e.g., Node.js, Python), wrap your insert operations in try-catch blocks to handle potential errors like duplicate keys or connection issues.
- Schema Validation: For production applications, consider using MongoDB’s Schema Validation feature to enforce a consistent structure for your documents, preventing accidental insertion of malformed data.
Common Errors
Section titled “Common Errors”- Duplicate Key Error (E11000): This occurs if you try to insert a document with an
_idthat already exists in the collection. Ensure your_idvalues are unique. - Write Concern Failed: This error can occur in replica sets if the write operation cannot be confirmed by the number of nodes specified in the write concern. This typically points to a replication or network issue.
- Maximum BSON Size Exceeded: A single MongoDB document cannot exceed 16 MB. If you need to store larger data, consider using GridFS or breaking the data into multiple documents.