You are on page 1of 3

All MongoDb commands you will ever need

(MongoDb Cheatsheet)

1. Database Commands
View all databases
show dbs

Create a new or switch databases 


use dbName

View current Database


db

Delete Database 
db.dropDatabase
db.dropDatabase()
()

2. Collection Commands
Show Collections
show collections

Create a collection named 'comments'


db.createCollection
db.createCollection(('comments')
'comments')

Drop a collection named 'comments'


db.comments.drop
db.comments.drop()
()

3. Row(Document) Commands
Show all Rows in a Collection 
db.comments.find
db.comments.find()
()

Show all Rows in a Collection (Prettified)


db.comments.find
db.comments.find().
().pretty
pretty()
()
Find the first row matching the object
db.comments.findOne
db.comments.findOne({
({name
name:: 'Harry'})
'Harry'})

Insert One Row


db.comments.insert
db.comments.insert({ ({
        'name':
'name': 'Harry',
'Harry',
        'lang':
'lang': 'JavaScript',
'JavaScript',
        'member_since':
'member_since': 5
})

Insert many Rows


db.comments.insertMany
db.comments.insertMany([{ ([{
        'name':
'name': 'Harry',
'Harry',
        'lang':
'lang': 'JavaScript',
'JavaScript',
        'member_since':
'member_since': 5
        },
        {'name'
{'name':: 'Rohan',
'Rohan',
        'lang':
'lang': 'Python',
'Python',
        'member_since':
'member_since': 3
        },
        {'name'
{'name':: 'Lovish',
'Lovish',
        'lang':
'lang': 'Java',
'Java',
        'member_since':
'member_since': 4
}])

Search in a MongoDb Database


db.comments.find
db.comments.find({
({lang
lang::'Python'})
'Python'})

Limit the number of rows in output


db.comments.find
db.comments.find().
().limit
limit((2)

Count the number of rows in the output


db.comments.find
db.comments.find().
().count
count()
()

Update a row
db.comments.updateOne
db.comments.updateOne({ ({name
name:: 'Shubham'},
'Shubham'},
{$set:
$set: {'name'
{'name':: 'Harry',
'Harry',
        'lang':
'lang' 'JavaScript',
: 'JavaScript',
        'member_since':
'member_since': 51
}}, {upsert
{upsert:: true})
true})

Mongodb Increment Operator


db.comments.update
db.comments.update({ ({name
name:: 'Rohan'},
'Rohan'},
{$inc:{
$inc:{
        member_since:
member_since: 2
}})

Mongodb Rename Operator


db.comments.update
db.comments.update({ ({name
name:: 'Rohan'},
'Rohan'},
{$rename:{
$rename:{
        member_since:
member_since: 'member'
}})

Delete Row 
db.comments.remove
db.comments.remove({
({name
name:: 'Harry'})
'Harry'})

Less than/Greater than/ Less than or Eq/Greater than or


Eq
db.comments.find
db.comments.find({
({member_since
member_since:: {$lt
{$lt:: 90}})
90}})

db.comments.find
db.comments.find({
({member_since
member_since:: {$lte
{$lte:: 90}})
90}})

db.comments.find
db.comments.find({
({member_since
member_since:: {$gt
{$gt:: 90}})
90}})

db.comments.find
db.comments.find({
({member_since
member_since:: {$gte
{$gte:: 90}})
90}})

You might also like