MongoDB Commands Cheat Sheet

What is MongoDB?

MongoDB is an open-source document-oriented database that is designed to store a large scale of data and also allows you to work with that data very efficiently.

Features of MongoDB

1. It is a natural form to store data.
2. It is human-readable.
3. Structured and unstructured information can be stored in the same document.
4. You can nest JSON to store complex data objects.
5. JSON has a flexible and dynamic schema, so adding fields or leaving a field out is not a problem.
6. Documents map to objects in most popular programming languages.

 Cheetsheets

As a MongoDB novice, you’ll find a thorough list of all the MongoDB commands you’ll ever need in this post. This list includes practically all of MongoDB’s most often used commands.

I’ll assume you’re working in the ‘blog’ collection of a MongoDB database of your choice.

Database Commands

1. View all Database

show dbs

2. Create a new or switch databases

use dbName

3. View current database

db

4. Delete database

db.dropDatabase()
Collection Commands 

1. Show collections

show collections

2. Create a collection named ‘blog’

db.createCollection('blog')

3. Drop a collection named ‘blog’

db.blog.drop()
Row (Documents) commands

1. Shows all rows in a collection

db.blog.find()

2. Shows all rows in a collection (prettified)

db.blog.find().pretty()

3. Find the first row matching the object

db.blog.findOne({name: 'MongoDB'})

4. Insert one row

db.blog.insert({
    'author': 'Stuti',
    'category': 'database',
    'date_posted': 2022/15/2
 })

5. Insert many rows

db.blog.insertMany([{
    'name': 'Bibek',
    'expertise': 'JavaScript',
    'experience': 3
    }, 
    {'name': 'Rounak',
    'expertise': 'PHP',
    'experience': 2
    },
    {'name': 'Neri',
    'expertise': 'Java',
    'experience': 2
}])

6. Search in MongoDB database

db.blog.find({lang:'JavaScript'})

7. Limit the number of rows in the output

db.blog.find().limit(2)

8. Count the number of rows in output

db.blog.find().count()

9. Update a row

db.blog.update({name: 'Nishant'},
{'name': 'Bibek',
    'expertise': 'JavaScript',
    'experience': 3
}, {upsert: true})

MongoDB increment operator

db. blog.update({name: 'Rounak'},
{$inc:{
    experience: 2
}})

MongoDB rename operator

db.blog.update({name: 'Neri'},
{$rename:{
    experience: 3
}})

Delete Row

db.blog.remove({name: 'Neri'})

4 thoughts on “MongoDB Commands Cheat Sheet”

Leave a Comment

Scroll to Top