MongoDB Insert One Document


MongoDB Insert One Document

In MongoDB, the insertOne operation is used to insert a single document into a collection. This method is essential for adding individual records to MongoDB collections.


Syntax

db.collection.insertOne(document, options)

The insertOne method takes a document to specify the document to be inserted and an optional options parameter to customize the insertion.


Example MongoDB Insert One Document

Let's look at some examples of how to use the insertOne method in the programGuru collection in MongoDB:

1. Insert a Single Document

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

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


Full Example

Let's go through a complete example that includes switching to a database, creating a collection, and inserting a single document.

Step 1: Switch to a Database

This step involves switching to a database named myDatabase.

use myDatabase

In this example, we switch to the myDatabase database.

MongoDB Insert One Document

Step 2: Create a Collection

This step involves creating a new collection named programGuru in the myDatabase database.

db.createCollection("programGuru")

Here, we create a collection named programGuru.

MongoDB Insert One Document

Step 3: Insert a Document into the Collection

This step involves using the insertOne method to insert a document into the programGuru collection.

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

We insert a single document with the fields name, age, and email into the programGuru collection.

MongoDB Insert One Document

Conclusion

The MongoDB insertOne operation is crucial for adding individual records to collections. Understanding how to use this method allows you to efficiently add and manage data within MongoDB collections.