MongoDB Cheat Sheet

There a ’n’ number of database available. Every database have there own engine, drivers, syntax, structure and architecture.
MongoDB is a cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with schema. MongoDB is developed by MongoDB Inc. and licensed under the Server Side Public License (SSPL).
MongoDB is a general purpose, document-based, distributed database built for modern application developers and for the cloud era. No database makes you more productive.
Below is the list of some useful mongoDB commands that can help you while creating a project that are working on mongoDB
Start and stop the MongoDB Database:
sudo service mongod startsudo service mongod stop
Access the MongoDB database using Shell. By default mongodb start on port 27017, but we can change with the following command
mongo — host localhost:25875
Show all databases
show dbs

Select Database for further operations
To create a new database use ‘use <DATABASE_NAME>’ to create a new database. It will create a new database.
use mydb

Create User
To create a new user in MongoDB
db.createUser({"user": "alpha", "pwd": "alpha", "roles": ["readWrite", "dbAdmin"]})
To get the list of users you can use ‘show users’

Login with user and password with database

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
To insert a row use
db.<database_name>.insert({})
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"})
