Add Document

To add a document (or multiple documents) to a collection in MongoDB. We can use the "insertOne()" method to add a single document.

For Multiple Entries, we can use "insertMany()" method to add multiple documents.

Here's how we can do it using the MongoDB shell:

Connect to MongoDB:

Before creating a Collection(table) in MongoDB, First, we need to connect to our MongoDB instance using the MongoDB shell or a MongoDB client library using our programming language.

Using the Mongo shell, we can connect to a MongoDB server running on localhost by simply typing the `mongo` command in our terminal.

Example:

mongo

Example:

show dbs;

Once our connection is established successfully, we can check databases in MongoDB using the below command:

Example:

use your_database_name;

Example:

db

Switch or Create Database:

Switch to the database where you want to create the collection using the "use" command.

To check the current database name using mongo shell.

Example:

db.createCollection("your_collection_name")

Create Collection:

Use the "createCollection()" method to explicitly create a collection.

Example:

# Connect to MongoDB (assuming it's running locally on the default port)
mongo

# Switch to the desired database
use your_database_name

# Create a collection named your_collection_name
db.createCollection("your_collection_name")

The above command will create a collection in our specified Database.

Insert Document(s):

Use the appropriate method to add your document(s) to the collection.

insertOne: Insert a single document into a MongoDB collection using the `insertOne` Method.

insertMany: Insert multiple documents into a MongoDB collection using the `insertMany` Method.

Insert Document's Example:

# Connect to MongoDB (assuming it's running locally on the default port)
mongo

# Switch to the desired database
use your_database_name

# Insert a single document into a collection
db.your_collection_name.insertOne({name: "Alice Collin", age: 35, city: "New York", address: "Manhattan Park Avenue"})

# Insert multiple documents into a collection
db.your_collection_name.insertMany([
    {name: "Edward", age: 36, city: "Los Angeles", address: "Park Avenue 12th street"},
    {name: "Bella", age: 32, city: "Polo Alto", address: "Park Avenue 15th street"},
    {name: "Warner", age: 30, city: "Las Vegas", address: "Park Avenue 17th street"}
])

Note:

  • Replace "your_database_name" with the name of your database and "your_collection_name" with the name of your collection.

  • Update the document structure and values with your own data.

  • If the collection does not exist, MongoDB will create it automatically when you insert the first document.

  • MongoDB automatically assigns a unique _id field to each document if we do not provide one explicitly.

  • This "_id" field serves as the primary key for the document.

  • If we want to provide our own "_id", we can include it in the document.