MongoDB version From the Terminal (MongoDB CLI):
mongod --version or mongosh --version
Find mongo database folder on the Linux filesystem
grep -i dbPath /etc/mongod.conf
Go Inside the Mongo Shell to see collections
Create Or Switch Database
db.createCollection('products')
Get All Documents in a DB
Get All Documents format output nicely
db.collectionName.find().pretty()
db.products.find({ category: 'Gadgets' })
Find Documet with Partial Search
db.users.find({ name: /<full_or_partial_text>/i}) #(case insensitive)
db.products.insert({
{
name: 'iPhone 18 pro',
price: 200,
quantity: 4
}
})
Insert Multiple Documents
db.products.insertMany([
{
name: 'iPhone 18 pro',
price: 200,
quantity: 4
},
{
name: 'Samsung Pro',
price: 150,
quantity: 13
},
{
name: 'Tesla Pi',
price: 180,
quantity: 7
}
])
# asc
db.products.find().sort({ name: 1 }).pretty()
# desc
db.products.find().sort({ name: -1 }).pretty()
db.products.find().count()
db.products.find().limit(2).pretty()
db.products.find().limit(2).sort({ name: 1 }).pretty()
db.products.find().forEach(function(doc) {
print("Product Name: " + doc.name)
})
db.products.findOne({ category: 'Gadgets' })
db.products.update({ name: 'iPhone pro' },
{
name: 'iPhine pro latest',
price: 180,
date: Date()
},
{
upsert: true
})
db.products.update({ name: 'iPhone pro' },
{
$rename: {
price: 170
}
})
db.products.remove({ name: 'iPhone pro' })
Drop DB (switch to DB first with "use testDB"), then,