DEV Community

Cover image for MongoDB Cheat Sheet
Kamal Hossain
Kamal Hossain

Posted on • Updated on

MongoDB Cheat Sheet

MongoDB Cheat Sheet

Open MongoDB in cmd (For windows)

mongo
Enter fullscreen mode Exit fullscreen mode

If mongo is not recognized as an internal or external command, operable program or batch file, then do the followings from this blog

Show All Databases

show dbs
Enter fullscreen mode Exit fullscreen mode

Show Current Database

db
Enter fullscreen mode Exit fullscreen mode

Create Or Switch Database

use acme
Enter fullscreen mode Exit fullscreen mode

Drop Database🔴

> use mydb
> db.dropDatabase()
Enter fullscreen mode Exit fullscreen mode

Create Collection

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

Show Collections

show collections
Enter fullscreen mode Exit fullscreen mode

Drop Collection 🔴

> use mydb
> db.usersCollection.drop()
Enter fullscreen mode Exit fullscreen mode

Insert Row

db.posts.insert({
  title: 'Post One',
  body: 'Body of post one',
  category: 'News',
  tags: ['news', 'events'],
  user: {
    name: 'John Doe',
    status: 'author'
  },
  date: Date()
})
Enter fullscreen mode Exit fullscreen mode

Insert Multiple Rows

db.posts.insertMany([
  {
    title: 'Post Two',
    body: 'Body of post two',
    category: 'Technology',
    date: Date()
  },
  {
    title: 'Post Three',
    body: 'Body of post three',
    category: 'News',
    date: Date()
  },
  {
    title: 'Post Four',
    body: 'Body of post three',
    category: 'Entertainment',
    date: Date()
  }
])
Enter fullscreen mode Exit fullscreen mode

Get All Rows from a collection

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

Get All Rows from a collection Formatted

db.posts.find().pretty()
Enter fullscreen mode Exit fullscreen mode

Find Rows

db.posts.find({ category: 'News' })
Enter fullscreen mode Exit fullscreen mode

Sort Rows in a collection

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

Count Rows in a collection

db.posts.find().count()
db.posts.find({ category: 'news' }).count()
Enter fullscreen mode Exit fullscreen mode

Limit Rows in a collection

db.posts.find().limit(2).pretty()
Enter fullscreen mode Exit fullscreen mode

Chaining example

db.posts.find().limit(2).sort({ title: 1 }).pretty()
Enter fullscreen mode Exit fullscreen mode

Foreach

db.posts.find().forEach(function(doc) {
  print("Blog Post: " + doc.title)
})
Enter fullscreen mode Exit fullscreen mode

Find One Row

db.posts.findOne({ category: 'News' })
Enter fullscreen mode Exit fullscreen mode

Find Specific Fields

db.posts.find({ title: 'Post One' }, {
  title: 1,
  author: 1
})
Enter fullscreen mode Exit fullscreen mode

Update Row

db.posts.update({ title: 'Post Two' },
{
  title: 'Post Two',
  body: 'New body for post 2',
  date: Date()
},
{
  upsert: true
})
Enter fullscreen mode Exit fullscreen mode

Update Specific Field

db.posts.update({ title: 'Post Two' },
{
  $set: {
    body: 'Body for post 2',
    category: 'Technology'
  }
})
Enter fullscreen mode Exit fullscreen mode

Increment Field (\$inc)

db.posts.update({ title: 'Post Two' },
{
  $inc: {
    likes: 5
  }
})
Enter fullscreen mode Exit fullscreen mode

Rename Field

db.posts.update({ title: 'Post Two' },
{
  $rename: {
    likes: 'views'
  }
})
Enter fullscreen mode Exit fullscreen mode

Delete specific document from a collection

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

Sub-Documents

db.posts.update({ title: 'Post One' },
{
  $set: {
    comments: [
      {
        body: 'Comment One',
        user: 'Mary Williams',
        date: Date()
      },
      {
        body: 'Comment Two',
        user: 'Harry White',
        date: Date()
      }
    ]
  }
})
Enter fullscreen mode Exit fullscreen mode

Find By Element in Array (\$elemMatch)

db.posts.find({
  comments: {
     $elemMatch: {
       user: 'Mary Williams'
       }
    }
  }
)
Enter fullscreen mode Exit fullscreen mode

Add Index

db.posts.createIndex({ title: 'text' })
Enter fullscreen mode Exit fullscreen mode

Text Search

db.posts.find({
  $text: {
    $search: "\"Post O\""
    }
})
Enter fullscreen mode Exit fullscreen mode

Greater & Less Than

db.posts.find({ views: { $gt: 2 } })
db.posts.find({ views: { $gte: 7 } })
db.posts.find({ views: { $lt: 7 } })
db.posts.find({ views: { $lte: 7 } })
Enter fullscreen mode Exit fullscreen mode

Get database size and index size in MB (Megabytes)

db.stats(1024*1024);
Enter fullscreen mode Exit fullscreen mode

Export a collection in json format

mongoexport --db newdb -c usersCollection --out testBakcup.json
Enter fullscreen mode Exit fullscreen mode

Import a collection from json file

mongoimport --db newdb -c usersCollectiontwo --file test.json
Enter fullscreen mode Exit fullscreen mode

Export entire database including all collections (Local)

mongodump --db newdb
Enter fullscreen mode Exit fullscreen mode

Export entire database including all collections (Cluster)

mongodump --uri="mongodb+srv://<Name>:<Password>@cluster0-pk6qf.mongodb.net/<DB_YOU_WANT_TO_EXPORT>?retryWrites=true&w=majority"
Enter fullscreen mode Exit fullscreen mode

ref1

use --collection <collection_name> for only specific collection

Import entire database including all collections

mongorestore --db deleteme dump/newdb
Enter fullscreen mode Exit fullscreen mode

newdb is the folder name that holds the database (deleteme) related files (.bson) etc.
To override same document with _id use this method

Connect to cloud mongodb cluster from mongo shell

mongo "mongodb+srv://cluster0.g1re8.mongodb.net/<dbname>" --username <check_mongo_cloud_connect_shell>
Enter fullscreen mode Exit fullscreen mode

Useful resources

Posted in • dev.to • gist.github.com

Oldest comments (0)