FOR QUICK REFERENCE
Complete MongoDB Cheatsheet
Published in
2 min readMar 17, 2023
All MongoDB commands you’ll ever need
1. Database Commands
View all databases
show dbs
Create a new or switch databases
use dbName
View current database
db
Delete database
db.dropDatabase()
2. Collection Commands
Show Collections
show collections
Create a new collection named ‘names’
db.createCollection('names')
Drop a collection named ‘names’
db.names.drop()
3. Row (Document) Commands
Show all Rows in a Collection
db.names.find()
Show all Rows in a Collection
db.names.find()
Show all Rows in a Collection (Prettified)
db.names.find().pretty()
Find the first row matching the object
db.names.findOne({name: 'Jim'})
Insert One Row
db.names.insert({
'name': 'Jimmy',
'language': 'Python',
'member_since': 5
})
Insert many Rows
db.names.insertMany([{
'name': 'Jimmy',
'language': 'Python',
'member_since': 5
},
{'name': 'Gabriel',
'language': 'Javascript',
'member_since': 8
},
{'name': 'Ryan',
'language': 'Java',
'member_since': 2
}])
Search in a database
db.names.find({language:'Python'})
Limit the number of rows in the output
db.names.find().limit(2)
Count the number of rows in the output
db.names.find().count()
Update a row
db.names.updateOne({name: 'Gabriel'},
{$set: {'name': 'Gabriel',
'language': 'JavaScript',
'member_since': 9
}}, {upsert: true})
Increment Operator
db.names.update({name: 'Ryan'},
{$inc:{
member_since: 2
}})
Rename Operator
db.names.update({name: 'Ryan'},
{$rename:{
member_since: 'member_terminated'
}})
Delete Row
db.names.remove({name: 'Jimmy'})
Less than Operator
db.names.find({member_since: {$lt: 8}})
Greater than Operator
db.names.find({member_since: {$gt: 8}})
Less than or equal Operator
db.names.find({member_since: {$lte: 8}})
Greater than or equal Operator
db.names.find({member_since: {$gte: 8}})
Other MongoDB commands can be found in the MongoDB documentation: https://www.mongodb.com/docs/manual
Support my work by buying me a Pizza: https://www.buymeacoffee.com/shubhrojyotidey