MongoDB: shell commands examples
Here are examples of common operations within the MongoDB Shell (mongosh):
1. Database Management:
show databases.
show dbs
- Switch to a database (or create if it doesn't exist):
use myDatabase
Show current database.
db
2. Collection Management:
Show collections in the current database.
show collections
Create a new collection.
db.createCollection("myCollection")
3. Data Manipulation (CRUD Operations):
Insert a single document.
db.myCollection.insertOne({ name: "Alice", age: 30, city: "New York" })
Insert multiple documents.
db.myCollection.insertMany([
{ name: "Bob", age: 25, city: "London" },
{ name: "Charlie", age: 35, city: "Paris" }
])
Find all documents in a collection.
db.myCollection.find()
Find documents with specific criteria.
db.myCollection.find({ age: { $gt: 28 } }) // Find documents where age is greater than 28
Find documents and project specific fields.
db.myCollection.find({}, { name: 1, city: 1, _id: 0 }) // Include name and city, exclude _id
Update a single document.
db.myCollection.updateOne({ name: "Alice" }, { $set: { age: 31 } })
Update multiple documents.
db.myCollection.updateMany({ city: "London" }, { $set: { status: "active" } })
Delete a single document.
db.myCollection.deleteOne({ name: "Bob" })
Delete multiple documents.
db.myCollection.deleteMany({ status: "inactive" })
4. Utility Commands:
Clear the shell screen.
cls
exit the shell.
exit