Skip to content

Instantly share code, notes, and snippets.

@fabecerram
Last active November 12, 2022 16:16
Show Gist options
  • Save fabecerram/a9eaeb59c7b385883548c17a79ca5747 to your computer and use it in GitHub Desktop.
Save fabecerram/a9eaeb59c7b385883548c17a79ca5747 to your computer and use it in GitHub Desktop.
MongoDB Cheat Sheet

MongoDB Cheat Sheet

The information in this quick guide is educational in nature, and is intended primarily for students and software developers who start with MongoDB, specifically with the use of MongoSH, for this reason information regarding database administration, clustering, tuning, or other advanced features is not included.


Databases

Show All Databases

show dbs

Show Current Database

db

Create Or Switch Database

use myMongoDB

Drop Database

db.dropDatabase()

Collections

Create Collection

db.createCollection('myCollection')

Show Collections

show collections

Count of documents that match the query for a collection or view

db.myCollection.countDocuments({})
db.myCollection.countDocuments(filtro)

Delete a Collection

db.myCollection.drop()

Documents

Basic Structure of filters or query selection criteria

# Relational Operator

Equal (=)                           { field: value }
Less Than (<)                       { field: { $lt:value }}
Less Than Equal (<=)                { field: { $lte:value }}
Greater Than (>)                    { field: { $gt:value }}
Greater Than Equal (>=)             { field: { $gte:value }}
Not Equal (!=)                      { field: { $ne:value }}

Values in an array                  { field: { $in: [ value, value, value ]}}
Values not in array                 { field: { $nin: [ value, value, value ]}}

# Logical operators

AND                                 { $and: [ { field:value }, { field:value }, { field:value } ] }
OR                                  { $or: [ { field:value }, { field:value }, { field:value } ] }
NOR                                 { $nor: [ { field:value }, { field:value }, { field:value } ] }
NOT                                 { $not: [ { field:value }, { field:value }, { field:value } ] }

Insert Documents

Inserts a Single Document into a Collection

db.myCollection.insertOne({ 
  item: "card", 
  qty: 15 
})

Inserts Multiple Documents into a Collection

db.myCollection.insertMany([
  { 
    item: "card", 
    qty: 15 
  },
  { 
    item: "box", 
    qty: 20 
  },
  { 
    item: "envelopes", 
    qty: 30 
  }
])

Select Documents

Get All Documents in a Collection

db.myCollection.find()

Get All Documents Formatted

db.myCollection.find().pretty()

Find Documents

db.myCollection.find({ item: "card" })

Find Documents by MongoDB Id

db.myCollection.find({ _id: ObjectId("616d7ca2cb1032dfa6345840") })

Greater & Less Than

db.myCollection.find({ qty: { $gt: 2 } })
db.myCollection.find({ qty: { $gte: 7 } })
db.myCollection.find({ qty: { $lt: 7 } })
db.myCollection.find({ qty: { $lte: 7 } })

Sort Documents

# asc
db.myCollection.find().sort({ item: 1 }).pretty()

# desc
db.myCollection.find().sort({ item: -1 }).pretty()

Count Documents

db.myCollection.find().count()
db.myCollection.find({ item: "card" }).count()

Specify the Maximum Number of Documents

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

Specify a Number of Documents to Skip in the Results

db.myCollection.find().skip(2).pretty()

Chaining

db.myCollection.find().limit(2).sort({ item: 1 }).pretty()

Foreach

db.myCollection.find().forEach(function(doc) {
  print("Item name: " + doc.item)
})

Find an Returns One Document

db.myCollection.findOne({ item: "card" })

Find - Show Specific Fields (Projections)

# Unless the _id field is explicitly excluded in the projection document, the _id field is returned.
# 0 = Hide field, 1 = Show field

db.myCollection.find({ item: "card" }, {
  _id: 0,
  item: 1
})

Find By Element in Array ($elemMatch)

db.myCollection.find({
  address: {
     $elemMatch: {
       name: "Office"
       }
    }
  }
)

Find by Text Search

db.myCollection.find({
  $text: {
    $search: "\"card\""
    }
})

Update Documents

Update One Document Or Create a New One if the Filter Does Not Match

db.myCollection.updateOne({ item: "card" },
{
  item: "card"
  qty: 50
},
{
  upsert: true
})

Update Documents - Add or Update Specific Fields

db.myCollection.updateOne({ item: "card" },
{
  $set: {
    qty: 50
  }
})

db.myCollection.updateMany({ },
{
  $set: {
    age: 0
  }
})

Update Documents - Delete a Specific Field

db.myCollection.updateOne({ item: "card" },
{
  $unset: {
    qtyii: ""
  }
})

db.myCollection.updateMany({ },
{
  $unset: {
    qtyii: ""
  }
})

Increment Field ($inc)

db.myCollection.updateOne({ item: "card" },
{
  $inc: {
    qty: 5
  }
})

Rename Field

db.myCollection.update({ item: "card" },
{
  $rename: {
    qtyii: 'qty'
  }
})

Update Sub-Documents

db.myCollection.updateOne({ userName: 'Jhon_Doe' },
{
  $set: {
    address: [
      {
        name: "Home",
        mainAddress: "20341 My home",
        phone: "123456789"
      },
      {
        name: "Office",
        mainAddress: "20341 My Office",
        phone: "123456789"
      }
    ]
  }
})

Delete Documents

Delete Document

db.myCollection.deleteOne({ _id: ObjectId("616d7ca2cb1032dfa6345840") })

Delete All Documents in a Collection

db.myCollection.deleteMany({})


Creator

Fabian A. Becerra M. https://github.com/fabecerram


This information has been extracted from the official MongoDB documentation, for more details see the MongoSH manual at https://www.mongodb.com/docs/manual/reference/method/


Copyright and license

Code and documentation copyright 2019-2022 the authors. Code released under the MIT License.

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