Introduction
Learn how to insert documents into a MongoDB collection using the mongosh shell interface.
Connecting to MongoDB
Before inserting documents, ensure you are connected to your MongoDB server:
Example: Connecting to MongoDB
mongoshThis command starts the mongosh shell and connects to the default MongoDB server running locally.
Switching to a Database
Switch to the desired database where you want to insert documents using the use command:
Example: Switching to a Database
use mydatabaseThis command switches to the “mydatabase” database. Replace mydatabase with your database name.
Inserting Documents
To insert documents into a MongoDB collection, use the insertOne or insertMany method:
Example: Inserting a Single Document
db.mycollection.insertOne({
name: "John Doe",
age: 30,
status: "active"
})This command inserts a single document into the mycollection collection with fields name, age, and status.
Example: Inserting Multiple Documents
db.mycollection.insertMany([
{
name: "Jane Doe",
age: 25,
status: "inactive"
},
{
name: "Alice Smith",
age: 35,
status: "active"
}
])This command inserts multiple documents into the mycollection collection.
Verifying Insertion
Verify that the documents have been inserted by querying the collection:
Example: Querying Documents
db.mycollection.find()This command retrieves all documents from the mycollection collection. Verify that your inserted documents appear in the results.
Conclusion
Inserting documents into a MongoDB collection using mongosh is straightforward. After insertion, you can perform further queries and operations on your data.