MongoDB Cheatsheet


Show All Databases

show dbs

Show Current Database

db

Create Or Switch Database

use acme

Drop

db.dropDatabase()

Create Collection

db.createCollection('articles')

Show Collections

show collections

Insert Row

db.articles.insert({
  title: 'Article One',
  body: 'Body of Article one',
  category: 'News',
  tags: ['news', 'events'],
  user: {
    name: 'John Doe',
    status: 'author'
  },
  date: Date()
})

Insert Multiple Rows

db.articles.insertMany([
  {
    title: 'Article Two',
    body: 'Body of Article two',
    category: 'Technology',
    date: Date()
  },
  {
    title: 'Article Three',
    body: 'Body of Article three',
    category: 'News',
    date: Date()
  },
  {
    title: 'Article Four',
    body: 'Body of Article three',
    category: 'Entertainment',
    date: Date()
  }
])

Get All Rows

db.articles.find()

Get All Rows Formatted

db.find().pretty()

Find Rows

db.articles.find({ category: 'News' })

Sort Rows

# asc
db.articles.find().sort({ title: 1 }).pretty()
# desc
db.articles.find().sort({ title: -1 }).pretty()

Count Rows

db.articles.find().count()
db.articles.find({ category: 'news' }).count()

Limit Rows

db.articles.find().limit(2).pretty()

Chaining

db.articles.find().limit(2).sort({ title: 1 }).pretty()

Foreach

db.articles.find().forEach(function(doc) {
  print("Blog Article: " + doc.title)
})

Find One Row

db.articles.findOne({ category: 'News' })

Find Specific Fields

db.articles.find({ title: 'Article One' }, {
  title: 1,
  author: 1
})

Update Row

db.articles.update({ title: 'Article Two' },
{
  title: 'Article Two',
  body: 'New body for Article 2',
  date: Date()
},
{
  upsert: true
})

Update Specific Field

db.articles.update({ title: 'Article Two' },
{
  $set: {
    body: 'Body for Article 2',
    category: 'Technology'
  }
})

Increment Field ($inc)

db.articles.update({ title: 'Article Two' },
{
  $inc: {
    likes: 5
  }
})

Rename Field

db.articles.update({ title: 'Article Two' },
{
  $rename: {
    likes: 'views'
  }
})

Delete Row

db.articles.remove({ title: 'Article Four' })

Sub-Documents

db.articles.update({ title: 'Article One' },
{
  $set: {
    comments: [
      {
        body: 'Comment One',
        user: 'Mary Williams',
        date: Date()
      },
      {
        body: 'Comment Two',
        user: 'Harry White',
        date: Date()
      }
    ]
  }
})

Find By Element in Array ($elemMatch)

db.articles.find({
  comments: {
     $elemMatch: {
       user: 'Mary Williams'
       }
    }
  }
)

Add Index

db.articles.createIndex({ title: 'text' })

Text Search

db.articles.find({
  $text: {
    $search: "\"Article O\""
    }
})

Greater & Less Than

db.articles.find({ views: { $gt: 2 } })
db.articles.find({ views: { $gte: 7 } })
db.articles.find({ views: { $lt: 7 } })
db.articles.find({ views: { $lte: 7 } })