MongoDB Cheat Sheet

Start and stop the MongoDB Database:

sudo service mongod startsudo service mongod stop
mongo — host localhost:25875

Show all databases

show dbs
show dbs
use mydb

Create User

db.createUser({"user": "alpha", "pwd": "alpha", "roles": ["readWrite", "dbAdmin"]})

Show current Database

db

Creating Collection

db.createCollection(‘users’)

Show Collections

show tables
show collections
db.getCollectionNames() # this will also work to list the tables

Insert Row

db.users.insert({
id: 'User1',
name: 'Naresh Kumar',
mobile: '9099056681',
role: ['isadmin', 'true'],
date: Date()
})

Insert Multiple Row

db.users.insertMany(
[{
id: 'User1',
name: 'Naresh Kumar',
mobile: '9099056681',
role: ['isadmin', 'true'],
date: Date()
},
{
id: 'User2',
name: 'Jash',
mobile: '9568547854',
role: ['isadmin', 'false'],
date: Date()
},
{
id: 'User3',
name: 'Surbhi',
mobile: '9547123654',
role: ['isadmin', 'flase'],
date: Date()
}]
)

Get All rows

db.users.find()

Get All Rows Formatted

db.users.find().pretty()

Find Rows

db.users.find({id:”naresh”})

Sort Rows

# asc
db.users.find().sort({ title: 1 }).pretty()
# desc
db.users.find().sort({ title: -1 }).pretty()

Count Rows

db.users.find().count() #count all the rowsdb.users.find({name:”Surbhi”}).count() #count row with specific condition

Update Row

db.users.update({ id: 'User1' },
{
name: 'Naresh',
mobile: '9099056682',
date: Date()
},
{
upsert: true
})

Delete Row

db.users.remove({id:”User3"})

--

--

Security Analyst making safe cyberspace 4 people #cyber4people India

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store