DEV Community

loading...
Cover image for MongoDB cheatsheet

MongoDB cheatsheet

vishnuchilamakuru profile image Vishnu Chilamakuru Originally published at vishnuch.tech ・3 min read

MongoDB is an open-source document-oriented NoSQL database that is designed to store a large scale of data and also allows you to work with that data very efficiently. It stores data in the form of JSON documents. MongoDB provides a SQL-like query language to query records based on the internal structure of the document itself. Document stores provide high flexibility and are often used for working with occasionally changing data.

In this post, I will mention a few MongoDB commands which are used more frequently by the developers.

Index


Database Operations

1. Show All Databases

show dbs
Enter fullscreen mode Exit fullscreen mode

2. Show current Database

db
Enter fullscreen mode Exit fullscreen mode

3. Create or switch to new Database

use hashnode
Enter fullscreen mode Exit fullscreen mode

4. Delete Database

db.dropDatabase()
Enter fullscreen mode Exit fullscreen mode

Collections

1. Show All Collections of Current Database

show collections
Enter fullscreen mode Exit fullscreen mode

2. Create new collection

db.createCollection('posts')
Enter fullscreen mode Exit fullscreen mode

Create Documents

1. Insert One document

db.posts.insertOne(
   {title: "blog post title", body: "blog post content"}
)
Enter fullscreen mode Exit fullscreen mode

or

db.posts.insert(
   {title: "blog post title", body: "blog post content"}
)
Enter fullscreen mode Exit fullscreen mode

2. Insert Multiple document

db.posts.insert( [ 
    {title: "blog post 1 title", body: "blog post 1 content"},
    {title: "blog post 2 title", body: "blog post 2 content"},
])
Enter fullscreen mode Exit fullscreen mode

Read Documents

1. Find One document

db.posts.findOne()
Enter fullscreen mode Exit fullscreen mode

2. Find Multiple documents

db.posts.find()
/* returns a cursor - show 20 results - "it" to display more */
Enter fullscreen mode Exit fullscreen mode

3. Find Multiple documents with formatted json

db.posts.find().pretty()
/* returns a cursor - show 20 results - "it" to display more */
Enter fullscreen mode Exit fullscreen mode

4. Find documents by field value.

db.posts.find({'title' : 'blog 1 title'})
Enter fullscreen mode Exit fullscreen mode

Update Documents

1. Update one

db.posts.updateOne({"_id": 1}, {$set: {"title": 'updated title'}})
Enter fullscreen mode Exit fullscreen mode

2. Update Multiple

/* update only specific fields */ 
db.posts.update({"category": "technology"}, {$set: {"category": 'computer science'}})
Enter fullscreen mode Exit fullscreen mode

3. Upsert complete Row

db.posts.update({ '_id' : 1 },
{
  title: 'Post one',
  body: 'New body for post 1',
},
{
  upsert: true
})
Enter fullscreen mode Exit fullscreen mode

4. Increment Field Value

db.posts.update({ "_id": 1 },
{
  $inc: {
    views: 5
  }
})
Enter fullscreen mode Exit fullscreen mode

Delete Documents

1. Delete

db.posts.remove({ title: 'Post 1' })
Enter fullscreen mode Exit fullscreen mode

Sorting

Fetch results by sorting on field.

# ascending order
db.posts.find().sort({ title: 1 }).pretty()

# descending order
db.posts.find().sort({ title: -1 }).pretty()
Enter fullscreen mode Exit fullscreen mode

Limit and Offset

Fetch results by pagination.

/* Skip 3 results*/
db.posts.find({}).skip(10)

/* Fetch only 3 results*/
db.posts.find({}).limit(3)

/* Sort by title , Skip first 10 results, fetch only next 3 documents*/
db.posts.find({}).sort({"title": 1}).skip(10).limit(3)
Enter fullscreen mode Exit fullscreen mode

Add and Drop Index

1. Add Index

/* Create Index on single field */
db.posts.createIndex({"title": 1})  

/* Create compound Index */
db.posts.createIndex({"title": 1, "date": 1})  
Enter fullscreen mode Exit fullscreen mode

2. Drop Index

db.posts. dropIndex("title_1")  

Enter fullscreen mode Exit fullscreen mode

Range Queries

Find documents by range query

/* find posts where views are greater than 50 */
db.posts.find({'views' : { '$gt' : 50 }})

/* find posts where views are greater than or equal to 50 */
db.posts.find({'views' : { '$gte' : 50 }})

/* find posts where views are less than 50 */
db.posts.find({'views' : { '$lt' : 50 }})

/* find posts where views are less than or equal to 50 */
db.posts.find({'views' : { '$lte' : 50 }})
Enter fullscreen mode Exit fullscreen mode

Text Search

1. Create Text Index on field

db.posts.createIndex({content: "text"})
Enter fullscreen mode Exit fullscreen mode

2. Search by Text

db.posts.find({
  $content: {
    $search: "post content"
    }
})
Enter fullscreen mode Exit fullscreen mode

Thank you for reading

Hope you find these resources useful. If you like what you read and want to see more about system design, microservices, and other technology-related stuff... You can follow me on

Buy Me A Coffee

Discussion (1)

Collapse
bgrand_ch profile image
Benjamin Grand

Thanks a lot 👌

Forem Open with the Forem app