MongoDB useful cheat sheet
MongoDB is an open-source NoSQL database. It is a type of database that can manage document-oriented information. MongoDB has some strong use cases:
Following are some of the strong use cases:
- Schema-less design
- Scalability in managing Tera bytes of data
- Rapid replicaSet with high availability feature
- Sharding enables linear and scale out growth without running out of budget
- Support high write load
- Use of data locality for query processing
Following are some useful commands for MongoDB.
MongoDB Cheat Sheet
Show All Databases
show dbs
Show Current Database
db
Create Or Switch Database
use mydb
Drop
db.dropDatabase()
Create Collection
db.createCollection('users')
Show Collections
show collections
Insert Row
db.users.insert({ name: 'Joe Smith', state: 'active', date: Date() })
Insert Multiple Rows
db.users.insertMany([ { name: 'Jenny Smith', state: 'active', date: Date() }, { name: 'Cathy Cassidy', state: 'inactive', date: Date() } ])
Get All Rows
db.users.find()
Get All Rows Formatted
db.users.find().pretty()
Find Rows
db.users.find({ status: 'active' })
Sort Rows
# asc db.users.find().sort({ name: 1 }).pretty() # desc db.users.find().sort({ name: -1 }).pretty()
Count Rows
db.users.find().count() db.users.find({ status: 'active' }).count()
Limit Rows
db.users.find().limit(2).pretty()
Chaining
db.users.find().limit(2).sort({ name: 1 }).pretty()
Foreach
db.users.find().forEach(function(doc) { print("User name: " + doc.name) })
Find One Row
db.users.findOne({ status: 'active' })
Find Specific Fields
db.users.find({ name: 'Joe Smith' }, { name: 1, author: 1 })
Update Row
db.users.update({ name: 'Joe Smith' }, { name: 'Jenny Smith', date: Date() }, { upsert: true })
Update Specific Field
db.users.update({ name: 'Joe Smith' }, { $set: { name: 'Joe Smith', status: 'active' } })
Increment Field ($inc)
db.users.update({ name: 'Joe Smith' }, { $inc: { likes: 5 } })
Rename Field
db.users.update({ name: 'Joe Smith' }, { $rename: { likes: 'views' } })
Delete Row
db.users.remove({ name: 'Joe Smith' })