Connect & Check version :
mongo
mongosh
mongod
Database Commands
View all databases
show dbs
Create a new or switch databases
use dbName
View current Database
db
Delete Database
db.dropDatabase()
Collection Commands
Show Collections
show collections
Create a collection named 'comments’
db.createCollection('data')
Drop a collection named 'comments’
db.comments.drop()
Row(Document) Commands
Show all Rows in a Collection
db.comments.find()
Show all Rows in a Collection (Prettified)
db.comments.find().pretty()
Find the first row matching the object
db.comments.findOne({name: 'Manthan'})
Insert One Row
db.comments.insert({
'firstName': 'Manthan',
'lastName': 'Ank'
})
Insert many Rows
db.comments.insertMany(
[
{
'firstName': 'Manthan',
'lastName': 'Ank'
},
{
'firstName': 'Gagan',
'lastName': 'BA'
}
])
Search in a MongoDB Database
db.comments.find({lang:'JavaScript'})
Limit the number of rows in output
db.comments.find().limit(3)
Count the number of rows in the output
db.comments.find().count()
Update a row
db.comments.updateOne(
{name: 'Manthan'},
{$set: {
'name': 'Manthan',
'lang': 'JavaScript',
'mem_since': 1
}
},
{upsert: true}
)
MongoDB Increment Operator
db.comments.update(
{name: 'Manthan'},
{
$inc:{
mem_since: 2
}
}
)
MongoDB Rename Operator
db.comments.update(
{name: 'Manthan'},
{
$rename:{
mem_since: 'member'
}
}
)
Delete Row
db.comments.remove({name: 'Manthan'})
Less than/Greater than/ Less than or Eq/Greater than or Eq
db.comments.find({member_since: {$lt: 90}})
db.comments.find({member_since: {$lte: 90}})
db.comments.find({member_since: {$gt: 90}})
db.comments.find({member_since: {$gte: 90}})