Skip to content

Instantly share code, notes, and snippets.

@planetapex
Forked from bradtraversy/mongodb_cheat_sheet.md
Last active April 28, 2020 16:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save planetapex/4e7560f2f01ea9cb62784ccee58c310c to your computer and use it in GitHub Desktop.
Save planetapex/4e7560f2f01ea9cb62784ccee58c310c to your computer and use it in GitHub Desktop.
MongoDB Cheat Sheet

Mongo DB Shell Cheat Sheet

These commands are for MongoDB shell and not for the mongo db Node.js driver or mongoose package.

Setup the environment

The examples here uses this sample dataset. Please, follow the instructions to setup the sample collection.

This is quick start for developers who want to a be up and running in no time.

Refer to the original documentation for extensive examples and guidance.

Table of Contents:

Show All Databases

show dbs

Show Current Database

db
db.getName()

Create Or Switch Database

use acme

Drop a database

db.dropDatabase()

Create Collection

db.createCollection('posts')

Show Collections

show collections
db.getCollectionNames()

Insert Row

db.posts.insert({
'firstName' : 'Arvinda',
'lastName' : 'de Silva',
'email' : 'de Silva@yahoo.com',
'age' : 40,
'active' : false,
'tags' : [ 'migration',  'connect', 'Multi-channelled', 'maximize'],
'post' : 'Iure tenetur quo ea earum consequatur. \n \rDoloremque aut possimus. Delectus eos et eos soluta blanditiis enim accusantium',
'date' : Date(),
'comments': [
    {
        'user' : 'arvidr30',
        'comment' : 'Dolorum eum consequatur. Laborum qui et dolorem tempore quae similique aut sit.',
        'date' : Date()
    }
    ]
})

Insert Multiple Rows

db.posts.insertMany([
 {
'firstName' : 'Salem',
'lastName' : 'Gonzalo',
'email' : 'salemG@yahoo.com',
'age' : 40,
'active' : false,
'tags' : [ 'migration',   'complexity', 'maximize', 'Drives'],
'post' : 'Iure tenetur quo ea earum consequatur. \n \rDoloremque aut possimus. Delectus eos et eos soluta blanditiis enim accusantium',
'date' : Date(),
'comments': [
    {
        'user' : 'salloG123',
        'comment' : 'Dolorum eum consequatur. Laborum qui et dolorem tempore quae similique aut sit.',
        'date' : Date()
    }
    ]
},
{
'firstName' : 'Rodney',
'lastName' : 'de Souza',
'email' : 'rodneySouza@yahoo.com',
'age' : 40,
'active' : false,
'tags' : [ 'Integration', 'Belize Dollar', 'Checking Account'],
'post' : 'Iure tenetur quo ea earum consequatur. \n \rDoloremque aut possimus. Delectus eos et eos soluta blanditiis enim accusantium',
'date' : Date(),
'comments': [
    {
        'user' : 'rodeySou123',
        'comment' : 'Dolorum eum consequatur. Laborum qui et dolorem tempore quae similique aut sit.',
        'date' : Date()
    }
    ]
}
])

Important notes about the Find() Methods

  • to find based on a specific criteria we can make use of operator like , $all, $in ,$nin, $not, $regex, along with the and, or and nor operator, check relevant section and documentation.

  • Most of the find methods have the last argument containing options, you have to check the documentation on each. However,here is an example

db.posts.find({firstName:'John'}, {firstName:1 , lastName:1})

The second object {firstName:1 , lastName:1} is the projection. See some explantion below.

Here are the most common options with explanations:

Option Explanation
projection <document> A subset of fields to return.
sort <documet> Specifies a sorting order for the documents matched by the filter
upsert boolean When true,Creates a new document if no documents match the filter.NB:To avoid multiple upserts, ensure that the filter fields are uniquely indexed.
returnNewDocument boolean When true, returns the updated/inserted(upsert above) document instead of the original document.
  • if the find method performs some update operation, there may be an upsert option, check the explanation the options table.
  • There is also chaining of methods available. So you can process the results further, after they are found. Check Chaining of Methods section

Here is a simple example:

  • Find post with firtName = John
  • Show firstName and LastName fields only
  • Then sort the result by lastName descending.
db.posts.find({firstName:'John'}, {_id:0,firstName:1 , lastName:1}).sort({lastName:-1})

Get All Rows

db.posts.find()

Get All Rows Formatted

db.find().pretty()

Find Specific Rows

db.posts.find({ firstName: 'John'})

Chaining of Methods

  • Here results are found, we start chainging by
  • limiting the result to show 2 documents
  • and sorting it by firstName descending
  • then prettifying the result
db.posts.find().limit(2).sort({ firstName: 1 }).pretty()

Sort Rows

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

Count Rows

db.posts.find().count()
db.posts.find({ firstName: 'John' }).count()

Limit Rows

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

Find Nested Objects

db.posts.find({ 'comments.user':'Lucio67'})

Find Array by values

Arrays documentation

Some examples:

Exactly the same array

db.posts.find( { tags: [ "collaborative", "Product" ] } )

Find posts with tags containing a specified(one) value, besides other values:

db.posts.find( { tags: "Product" } )

Find posts with tags containing either values, i.e. either "collaborative" OR "Product"

db.posts.find({ tags: { $in: [  "collaborative", "Product" ]}} )

Find posts with tags containing both values, i.e. either "collaborative" AND "Product":

db.posts.find( { tags: {$all : [ "collaborative", "Product" ] }} )

We can specify conditions as well. Check the documentation for complete examples. Here are some examples, though not related to our collection "posts" but showing what is possible:

  • single conditions
  • Multiple conditions
  • Multiple conditions using $elemMatch
  • Finding by array index position
  • Finding by array size
db.inventory.find( { dim_cm: { $gt: 25 } } )
db.inventory.find( { dim_cm: { $gt: 15, $lt: 20 } } )
db.inventory.find( { dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } } )
db.inventory.find( { "dim_cm.1": { $gt: 25 } } )
db.inventory.find( { "tags": { $size: 3 } } )

Find By Element in Array ($elemMatch)

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

Find Multiple using Operator And | OR

AND and OR are both array of Objects

$and: [... {}]
$or: [... {}] 

Here is an example: Find all document which have

  • firstName OR lastName as John And
  • is Either active OR age is Greater Than 45
  • then display only these Fields
    • firstName, lastName , age, active
  • Then prettify the result
db.posts.find({
        $and : [
            { $or : [ { firstName :'John' }, { lastName :'John' } ] },
            { $or : [ { active : true }, { age : { $gt : 45 } } ] }
        ]
    } ,{firstName:1,lastName:1, active:1, age:1}).pretty()

Using the implicit AND (directly Specifying the or statements)

db.posts.find({
    $or : [ {firstName: 'John'},{lastName:  'John'} ],
    $or : [ {active : true }, { age : { $gt : 45 } }] 
}, {firstName:1,lastName:1, active:1, age:1}).pretty()

Find using Operator - Not

All the posts that are not active, active is not true:

db.posts.find( {"active": { $not: /^t.*/}}).pretty();

Find using Operator - IN and Not IN

All the posts where the age is 30,40,45 and similarly for not in:

db.posts.find({"age" : { $in : [30,40,45]}}).count()
db.posts.find({"age" : { $nin : [30,40,45]}}).count()

Text Search and Add Index

db.posts.createIndex({ firstName: 'text' })
db.posts.find({
  $text: {
    $search: '\'Post O\''
    }
})

Find using Regex pattern matching

Regex can be pretty daunting at times, so here are a few links to work with:

Monog Regex Documenation examples

Regexr for building regex

  • In regexr, we put test data on the multiline, just make sure to enable the multiline option and global option accordingly if needed

Example with regexr

All the posts where the firstName starts with the alphabet A

So,put in the text area some examples Alpa Allo Asgard

Then enable global and multiline options.

In the regex field type : ^A.*

We will be able to see the result of selected.

Now put it in the mongo Db:

db.posts.find( {"firstName": { $regex: /^A.*/}}).pretty();

BTW, in the above example in Regexr, we thought of multiline as separate document with firsName represented on each line. If you have some large field in the document like db.posts.post, which is multiline , and you want to search in this multiline field , we have option like { $regex: /^A.*/m} , notice the m. checkout the documentation.

Find using operator Greater & Less Than

db.posts.find({ age: { $gt: 45} })
db.posts.find({ age: { $gte: 40 } })
db.posts.find({ age: { $lt: 35 } })
db.posts.find({ age: { $lte: 35 } })

Find and Show Specific Fields

projection is what(Fields) to return

db.collection.find(query,projection) 
db.posts.find({ firstName: 'John' }, {
  _id:0,
  firstName: 1,
  age: 1
})

findAndModify()

Find One Row > And (update | Replace | Delete)

For each of these example run the db.posts.find({}) and just pick some object_ids to work with.

Find One

This returns the first document according to the natural order which reflects the order of documents on the disk.

db.posts.findOne({ active: true })

Find One And Delete

db.posts.findOneAndDelete({_id : ObjectId("5ea221bca66626db52fe02b8")})

Find One And Replace

db.posts.findOneAndReplace({_id :  ObjectId("5ea221bca66626db52fe02b9")}, 
{
'firstName' : 'Ruppet2',
'lastName' : 'Magrega2',
'email' : 'ruppetMag@yahoo.com',
'age' : 35,
'active' : false,
'tags' : [ 'Integration', 'Belize Dollar', 'Checking Account'],
'post' : 'Iure tenetur quo ea earum consequatur. \n \rDoloremque aut possimus. Delectus eos et eos soluta blanditiis enim accusantium',
'date' : Date(),
'comments': [
    {
        'user' : 'ruppetMag345',
        'comment' : 'Dolorum eum consequatur. Laborum qui et dolorem tempore quae similique aut sit.',
        'date' : Date()
    }
    ]
} ,
{returnNewDocument : true}  
)

Find One And Update

db.posts.findOneAndUpdate()

Foreach

db.posts.find().forEach(function(doc) {
  print('User: ' + doc.firstName + ' ' + doc.lastName)
})
db.posts.find({firstName : 'John'}).forEach(printjson);

Update(Replace) All Rows

Check update(modify) Specific Field for updating specific fields.

This will update(replace) with the new document, all the rows that it matched(found).

If the new document is missing fields , then all the matched rows will be missing the fields as it replaces.

db.posts.update({ {_id :  ObjectId("5ea221bca66626db52fe02b9") },
{
'firstName' : 'Ruppet2',
'lastName' : 'Magrega2',
'email' : 'ruppetMag@yahoo.com',
'age' : 35,
'active' : false,
'tags' : [ 'Integration', 'Belize Dollar', 'Checking Account'],
'post' : 'Iure tenetur quo ea earum consequatur. \n \rDoloremque aut possimus. Delectus eos et eos soluta blanditiis enim accusantium',
'date' : Date(),
'comments': [
    {
        'user' : 'ruppetMag345',
        'comment' : 'Dolorum eum consequatur. Laborum qui et dolorem tempore quae similique aut sit.',
        'date' : Date()
    }
    ]
},
{
  upsert: true
})

Update(modify) Specific Field

Update active to true where , firstName = John and age is between 35 and 40

db.posts.update(
    {
        'firstName' : 'John',
          age' :{$gte : 35, $lte : 40}
    }   
    ,
{
  $set: {
    active: true
    
  }
})

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

Increment Field ($inc)

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

Rename Field

Rename the field active to available for all the documents.

db.posts.update({},
{
  $rename: {
    active: 'available'
  }
})

Delete Row/Document

db.posts.remove({ title: 'Post Four' })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment