Skip to content

Instantly share code, notes, and snippets.

@yaronrl
Forked from bradtraversy/mongodb_cheat_sheet.md
Last active May 31, 2021 02:01
Show Gist options
  • Save yaronrl/df9edbd4a26152a7da5010443f1c32cc to your computer and use it in GitHub Desktop.
Save yaronrl/df9edbd4a26152a7da5010443f1c32cc to your computer and use it in GitHub Desktop.
MongoDB Cheat Sheet

MongoDB Cheat Sheet

Show All Databases

show dbs

Show Current Database

db

Create Or Switch Database

use acme

Drop

db.dropDatabase()

Create Collection

db.createCollection("posts")

Show Collections

show collections

Insert Row

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

This is done using an array

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

Get All Rows

Stops at the cursor

db.posts.find()

Return an array with all the documents

db.posts.find().toArray()

Get All Rows Formatted

db.posts.find().pretty()

Find Rows

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

Sort Rows

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

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

Find One Row

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

Find Specific Fields (projection)

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

Exclude the ID field

db.posts.find({ title: "Post One" }, {
  title: 1,
  author: 1,
  _id: 0
})

Update Row

Implicit change

db.posts.update({ title: "Post Two" },
{
  title: "Post Two",
  body: "New body for post 2",
  date: Date()
},
{
  upsert: true
})

Update Specific Field

if the field after the $set doesn"t exist, it will be created automatically.

db.posts.update({ title: "Post Two" },
{
  $set: {
    body: "Body for post 2",
    category: "Technology"
  }
})

Explicit change

db.posts.updateOne({ title: "Post Two" },
{
  $set: {
    body: "Body for post 2",
    category: "Technology"
  }
})

Update All Rows

db.posts.updateMany({},
{
  $set: {
    marker: "toDelete"
  }
})

Increment Field ($inc)

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

Rename Field

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

Replace Object

db.posts.replaceOne({ "_id" : ObjectId("60b2e815bb881b05ffc093ee")},
{
        "departureAirport" : "MUC",
        "arrivalAirport" : "SFO",
        "aircraft" : "Airbus A380",
        "distance" : 12000,
        "intercontinental" : true,
        "status" : {
                "description" : "on-time",
                "lastUpdated" : "1 hour ago",
                "details" : {
                        "responsible" : "Yaron Levi"
                }
       )

Delete Row

db.posts.remove({ title: "Post Four" })
db.posts.deleteOne({ title: "Post Four" })

Delete Many Rows

db.posts.deleteMany({marker: "toDelete"})

Delete All Rows

db.posts.deleteMany({})

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

Lists (Arrays)

db.posts.updateOne({ title: "Post One" },
{
  $set: {
    tags: [
      "sports", "cooking"
    ]
  }
})

Fetch the list from a document

db.posts.findOne({ title: "Post One" }).tags 

Find the document that contains a value in its list

db.posts.find({ tags: "sports" }).pretty() 

Find the document with an data from a sub-document

db.flightData.find({"status.description":"on-time"}).pretty()

Find By Element in Array ($elemMatch)

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

Add Index

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

Text Search

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 } })
@yaronrl
Copy link
Author

yaronrl commented May 31, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment