⬅ Previous Topic
Using MongoDB CompassNext Topic ⮕
Insert Operations in MongoDB⬅ Previous Topic
Using MongoDB CompassNext Topic ⮕
Insert Operations in MongoDBThe MongoDB Shell (mongosh
) is an interactive command-line interface where you can connect to your MongoDB server, run queries, and manage your databases. It's one of the fastest ways to interact with MongoDB and is highly recommended for beginners to understand the core operations.
After installing MongoDB, open your terminal or command prompt and run:
mongosh
This will connect you to the local MongoDB server by default.
Output:
Current Mongosh Log ID: 6627c54f3c7f1c9a69c6e98f Using MongoDB: 7.0.0 Using Mongosh: 2.0.0 test>
When you open mongosh
, it connects to the default test
database. To check which database you're currently using, type:
db
Output:
test
Use the use
command to switch to a different database. If it doesn't exist, MongoDB will create it when you first store data.
use studentDB
Output:
switched to db studentDB
Question: What happens if the database doesn't exist yet?
Answer: MongoDB creates it automatically when you insert the first piece of data.
To insert data, use insertOne()
or insertMany()
on a collection. If the collection doesn’t exist, it is automatically created.
db.students.insertOne({
name: "Alice",
age: 22,
department: "Computer Science"
});
Output:
{ acknowledged: true, insertedId: ObjectId("6627c5e93c7f1c9a69c6e993") }
This command created a new students
collection and added one document to it.
Use the find()
method to display all documents in a collection:
db.students.find()
Output:
[ { _id: ObjectId("6627c5e93c7f1c9a69c6e993"), name: "Alice", age: 22, department: "Computer Science" } ]
Question: What is _id
?
Answer: MongoDB automatically assigns a unique _id
to every document as its primary key.
Insert several records at once with insertMany()
:
db.students.insertMany([
{ name: "Bob", age: 24, department: "Physics" },
{ name: "Charlie", age: 23, department: "Math" }
]);
Output:
{ acknowledged: true, insertedIds: { '0': ObjectId("..."), '1': ObjectId("...") } }
To search for specific documents, pass a query object to find()
:
db.students.find({ department: "Physics" })
Output:
[ { _id: ObjectId("..."), name: "Bob", age: 24, department: "Physics" } ]
show dbs
– Lists all databasesshow collections
– Lists all collections in the current DBdb.dropDatabase()
– Deletes the current databasedb.collection.drop()
– Deletes a specific collectionThe MongoDB Shell gives you complete control over your database via command-line. You learned how to start the shell, switch databases, create collections, insert and query documents.
⬅ Previous Topic
Using MongoDB CompassNext Topic ⮕
Insert Operations in MongoDBYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.