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:
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.
mongo
Once our connection is established successfully, we can check databases in MongoDB using the below command:
show dbs;
Switch to the database where you want to create the collection using the "use" command.
use your_database_name;
To check the current database name using mongo shell.
db
Use the "createCollection()" method to explicitly create a collection.
db.createCollection("your_collection_name")
# 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.
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.
# 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" } )
insertMany: Insert multiple documents into a MongoDB collection using the `insertMany` Method.
# 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" } ])
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 data.