The MongoDB Shell connects to mongodb://127.0.0.1:27017 by default.
mongo
mongo "mongodb://127.0.0.1:27017"
To connect to MongoDB Atlas, use the following command:
mongo "mongodbURI" --username <user>
To show all databases in MongoDB, use the following command:
show databases
To display the current database, use this command:
db
To create or switch to a new database, simply use:
use <database_name>
To delete a database in MongoDB, use the following command:
db.dropDatabase()
show collections
db.createCollection("newCollection")
db.collection.insertOne({ name: "John Doe", age: 30 })
db.collection.insertMany([
{ name: "Alice", age: 25 },
{ name: "Bob", age: 28 }
])
db.collection.findOne({ name: "John Doe" })
db.collection.find({ age: { $gte: 25 } })
db.collection.find({ name: "Alice" })
db.collection.find({ age: 30 })
db.collection.find({ hobbies: "reading" })
db.collection.updateOne(
{ name: "John" },
{ $set: { age: 30 } }
)
db.collection.updateMany(
{ isActive: true },
{ $set: { status: "active" } }
)
db.collection.updateOne(
{ name: "Jane" },
{ $inc: { score: 5 } }
)
db.collection.updateMany(
{},
{ $rename: { oldFieldName: "newFieldName" } }
)
db.collection.updateOne(
{ "profile.username": "john_doe" },
{ $set: { "profile.age": 25 } }
)
db.collection.deleteOne(
{ name: "John" }
)
db.collection.countDocuments()
db.collection.countDocuments({ status: "active" })
db.collection.find().sort({ age: 1 })
db.collection.find().sort({ age: -1 })
db.collection.find().skip(7)
db.collection.find().limit(4)
db.collection.find().sort({ name: 1 }).skip(7).limit(4)
db.collection.createIndex({ name: 1 })
db.collection.createIndex({ age: 1, status: -1 })
db.collection.dropIndex({ name: 1 })
db.collection.createIndex({ description: "text" })
db.collection.find({ $text: { $search: "mongodb" } })
db.collection.find({ views: { $gt: 70 } })
db.collection.find({ views: { $gte: 70 } })
db.collection.find({ views: { $lt: 70 } })
db.collection.find({ views: { $lte: 70 } })
Congratulations! You’ve reached the end of . With these commands and techniques at your fingertips, you’re well-equipped to work efficiently with MongoDB in your projects.
Keep this cheat sheet handy as you build, query, and optimize your . And remember, is a powerful tool, so continue exploring its advanced features to learn its full potential.
Happy coding, and may your queries always be efficient! 🚀
Congratulations for completing this resource! Mark it as completed to track your progress.