w3resource

Guide to Using db.collection.insertOne in MongoDB


Understanding db.collection.insertOne() in MongoDB

The db.collection.insertOne() method in MongoDB is used to insert a single document into a collection. It’s an essential operation for adding data to a MongoDB database. This method ensures that the document is stored in the specified collection and assigns it a unique identifier (_id) if one is not provided.

Syntax:

db.collection.insertOne(
    <document>,
    {
      writeConcern: <document>
    }
)

Parameters:

Name Type Description
document Document The document to insert into the collection. Must be a valid JSON object. If no _id field is provided, MongoDB automatically generates one.
writeConcern Document (Optional) Specifies the write concern for the operation, controlling the level of acknowledgment required from MongoDB. Example: { w: "majority", wtimeout: 5000 }.

Notes:

1. document:

  • This is the main input for the operation, defining the data to be stored in the collection.
  • MongoDB automatically validates the document format and rejects invalid structures.

2. writeConcern:

  • Ensures control over data durability and acknowledgment.
  • If omitted, the default write concern of the database is used.

Returns: A document containing

  • A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled.
  • A field insertedId with the _id value of the inserted document.

Compatibility:

You can use db.collection.insertOne() for deployments hosted in the following environments:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud.
  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB.
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB.

Behaviors:

Collection Creation

If the collection does not exist, then the insertOne() method creates the collection.

_id Field

If the document does not specify an _id field, then mongod will add the _id field and assign a unique ObjectId() for the document before inserting. Most drivers create an ObjectId and insert the _id field, but the mongod will create and populate the _id if the driver or application does not.

If the document contains an _id field, the _id value must be unique within the collection to avoid duplicate key error.

Explainability

insertOne() is not compatible with db.collection.explain().

Error Handling

On error, db.collection.insertOne() throws either a writeError or writeConcernError exception.

Schema Validation Errors

If your collection uses schema validation and has validationAction set to error, inserting an invalid document throws a MongoServerError and db.collection.insertOne() fails.

Transactions

db.collection.insertOne() can be used inside distributed transactions.


Example Usage

Basic Example

Code:

// Insert a document into the 'users' collection
db.users.insertOne({
  name: "Kshitij Miriam", // Name field
  age: 30,         // Age field
  email: "[email protected]" // Email field
})

Explanation:

  • The users collection is the target collection.
  • The document contains three fields: name, age, and email.
  • If the operation succeeds, MongoDB returns an acknowledgment with an _id field.

Insert with Custom _id

Code:

// Insert a document with a custom _id
db.users.insertOne({
  _id: "user123",   // Custom identifier
  name: "Kshitij Miriam", // Name field
  age: 28           // Age field
})

Explanation:

  • A custom _id (user123) is specified.
  • MongoDB will not generate a new _id since one is provided.

Insert with Write Concern

Code:

// Insert a document with write concern options
db.users.insertOne(
  {
    name: "Vilma", // Name field
    age: 25        // Age field
  },
  {
    writeConcern: { w: "majority", wtimeout: 5000 } // Write concern options
  }
)

Explanation:

  • The writeConcern ensures the document is written to the majority of nodes.
  • The wtimeout specifies a timeout for the write operation (5000 milliseconds).

Returned Acknowledgment

When db.collection.insertOne() executes successfully, it returns an acknowledgment object:

Code:

{
  "acknowledged": true,
  "insertedId": ObjectId("648ec7f27d58e0001a3d2b3c")
}

Explanation:

  • acknowledged: Indicates the write operation was successful.
  • insertedId: The unique _id of the inserted document.

Error Scenarios

Duplicate _id Error

Code:

db.users.insertOne({
  _id: "user123", 
  name: "Duplicate User"
})

Error:

Code:

E11000 duplicate key error collection: test.users index: _id_ dup key: { _id: "user123" }

Reason:

  • The _id value user123 already exists in the users collection.
  • MongoDB does not allow duplicate _id values.

Invalid Document Structure

Code:

db.users.insertOne("InvalidDocument")

Error:

Code:

TypeError: Document must be a valid JSON object

Reason:

  • The argument provided is not a valid JSON object.

Best Practices

1. Schema Design:

  • Define a consistent document structure across your collections to avoid data inconsistencies.

2. Indexing:

  • Use indexing for fields like _id or frequently queried fields to improve performance.

3. Error Handling:

  • Always handle errors in application code to gracefully manage insert failures.

4. Validation Rules:

  • Use schema validation at the collection level to enforce data integrity.


Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/mongodb/mongodb-db-collection-insertone.php