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.
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.
Let's look at some examples of how to use the insertOne
method in the programGuru
collection in MongoDB:
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.
Let's go through a complete example that includes switching to a database, creating a collection, and inserting a single document.
This step involves switching to a database named myDatabase
.
use myDatabase
In this example, we switch to the myDatabase
database.
This step involves creating a new collection named programGuru
in the myDatabase
database.
db.createCollection("programGuru")
Here, we create a collection named programGuru
.
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.
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.