Skip to content

Instantly share code, notes, and snippets.

@eyal7773
Forked from bradtraversy/mongodb_cheat_sheet.md
Last active April 18, 2022 18:32
Show Gist options
  • Save eyal7773/6454823804913e9fa4a502b99aeb5c43 to your computer and use it in GitHub Desktop.
Save eyal7773/6454823804913e9fa4a502b99aeb5c43 to your computer and use it in GitHub Desktop.
MongoDB Cheat Sheet

MongoDB Cheat Sheet

Show All Databases

show dbs

Show Current Database

db

Clean screen

cls

Create Or Switch Database

use acme

Drop

db.dropDatabase()

Create Collection

db.createCollection('posts')

Show Collections

show collections

Insert Row

db.buzzwords.insertOne({word:'wow'})
db.posts.insertOne({
  title: 'Post One',
  body: 'Body of post one',
  category: 'News',
  tags: ['news', 'events'],
  user: {
    name: 'John Doe',
    status: 'author'
  },
  date: Date()
})

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()
  }
])

Delete single record

db.posts.deleteOne({_id:ObjectId("6255bd2679f2ed82ecf46087")})

Get All Rows

db.posts.find()

Get All Rows Formatted

Less relevant in Compass, but relevant in other Mongosh clients.

db.posts.find().pretty()

Find Rows

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

Find with regex - same as "LIKE" operator in SQL

db.posts.find({title: {$regex: '.*' + 'Three'}})

Sort Rows

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

Projection

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

you can also remove the _id which come by default :

db.posts.find({},{title:1, body:1, _id:0})

Count Rows

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

Limit Rows

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

Chaining

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

Foreach

db.posts.find().forEach(function(doc) {
  print("Blog Post: " + doc.title)
})
db.posts.find().forEach(x => print(x.title))

Find One Row

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

Update Row

db.posts.updateOne({title:'Post Two'},{ $set: {title:'Post 2'}})

In the next example, because of the upsert option, so it will create the new object, even if there is not such document currently in the db.

db.posts.updateOne({ title: 'Post BZZ' },
{ 
  $set: {
    title: 'Post BZZ',
    body: 'New body for post 333',
    date: Date()
  }
},
{
  upsert: true
})

Increment Field ($inc)

db.posts.updateOne({ title: 'Post Two' },
{
  $inc: {
    likes: 5
  }
})

Rename Field

db.posts.updateOne({ title: 'Post Two' },
{
  $rename: {
    likes: 'views'
  }
})

Sub-Documents

db.posts.updateOne({ title: 'Post One' },
{
  $set: {
    comments: [
      {
        body: 'Comment One',
        user: 'Mary Williams',
        date: Date()
      },
      {
        body: 'Comment Two',
        user: 'Harry White',
        date: Date()
      }
    ]
  }
}, 
{ upsert: true}
)

Find By Element in Array ($elemMatch)

From MongoDB Docs : The $elemMatch operator matches documents that contain an array field with at least one element that matches > all the specified query criteria.

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

Add Index

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

Text Search - Without specify field

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

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 } })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment