MongoDB Commands Simplified: The Only Cheat Sheet You'll Ever Need

MongoDB Commands Simplified: The Only Cheat Sheet You'll Ever Need

MongoDB: A Flexible and Scalable NoSQL Database

MongoDB is a popular NoSQL database that provides a flexible and scalable solution for storing and managing data. Unlike traditional relational databases, MongoDB stores data in flexible, JSON-like documents, allowing developers to easily change the structure of their data without the need for costly migrations.

Commands

Database Commands:

1) View all databases

show dbs

2) Create a new database or switch it

use dbName

3) View the current Database

db

4) Delete the Database

db.dropDatabase()

Collection Commands:

1) Show Collections

show collections

2) Create a collection named 'hashnode'

db.createCollection('hashnode')

3) Drop a collection named 'hashnode'

db.hashnode.drop()

Row Commands:

1) Show all Rows in a Collection

db.hashnode.find()

2) Show all Rows in a Collection (Prettified)

db.hashnode.find().pretty()

3) Getting the first row to match the object

db.hashnode.findOne({name: 'Suraj'})

4) Inserting a Single Row

db.hashnode.insert({
    'name': 'SURAJ',
    'lang': 'JavaScript',
    'age': 20
 })

5) Inserting Many Rows

db.hashnode.insertMany([{
    'name': 'SURAJ',
    'lang': 'JavaScript',
    'member_since': 20
    }, 
    {'name': 'RYAN',
    'lang': 'Python',
    'age': 30
    },
    {'name': 'Lasya',
    'lang': 'React',
    'age': 24
}])

6) Search in a MongoDB Database

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

7) Limit the number of Rows in the output

db.hashnode.find().limit(1)

8) Count the number of Rows in the output

db.hashnode.find().count()

9) Update a Row

db.hashnode.updateOne({name: 'Shubham'},
{$set: {'name': 'SURAJ',
    'lang': 'JavaScript',
    'age': 19
}}, {upsert: true})

10) Delete a Row

db.hashnode.remove({name: 'RYAN'})

Operator Commands:

1) Increment Operator

db.hashnode.update({name: 'RYAN'},
{$inc:{
    age: 23
}})

2) Rename Operator

db.hashnode.update({name: 'RYAN'},
{$rename:{
    age: 'age_value'
}})

3) Less than/Greater than/ Less than or Equal to/Greater than or Equal to

db.hashnode.find({age: {$lt: 30}})
db.hashnode.find({age: {$lte: 30}})
db.hashnode.find({age: {$gt: 30}})
db.hashnode.find({age: {$gte: 30}})

Conclusion

In conclusion, this MongoDB commands cheat sheet can be a handy resource for developers and database administrators who work with MongoDB. By memorizing or referencing these commands, you can more efficiently perform common tasks such as querying, inserting, updating, and deleting data in your MongoDB databases.

With this cheat sheet, you can quickly access and recall the MongoDB commands you need to work efficiently with your databases. However, always refer to the official MongoDB documentation for more in-depth information and best practices.

Until Next Time...