Skip to content

Instantly share code, notes, and snippets.

@psenger
Last active October 18, 2020 02:31
Show Gist options
  • Select an option

  • Save psenger/5bf6570eec7252c186c63e5ca9292da2 to your computer and use it in GitHub Desktop.

Select an option

Save psenger/5bf6570eec7252c186c63e5ca9292da2 to your computer and use it in GitHub Desktop.
[MongoDB Cheet Sheet] #MongoDB

MongoDB Cheet Sheet

BSON Types

Which of the following are valid types in BSON:

Type Number Alias Notes
Double 1 “double”
String 2 “string”
Object 3 “object”
Array 4 “array”
Binary data 5 “binData”
Undefined 6 “undefined” Deprecated.
ObjectId 7 “objectId”
Boolean 8 “bool”
Date 9 “date”
Null 10 “null”
Regular Expression 11 “regex”
DBPointer 12 “dbPointer” Deprecated.
JavaScript 13 “javascript”
Symbol 14 “symbol” Deprecated.
JavaScript code with scope 15 “javascriptWithScope” Deprecated in MongoDB 4.4.
32-bit integer 16 “int”
Timestamp 17 “timestamp”
64-bit integer 18 “long”
Decimal128 19 “decimal” New in version 3.4.
Min key -1 “minKey”
Max key 127 “maxKey”
  • byte 1 byte (8-bits)
  • int32 4 bytes (32-bit signed integer, two's complement)
  • int64 8 bytes (64-bit signed integer, two's complement)
  • uint64 8 bytes (64-bit unsigned integer)
  • double 8 bytes (64-bit IEEE 754-2008 binary floating point)
  • decimal128 16 bytes (128-bit IEEE 754-2008 decimal floating point)
  • ObjectId
  • String
  • Timestamp
  • Date

The field name _id is reserved for use as a primary key; its value must be unique in the collection, is immutable, and may be of any type other than an array.

Replication and Redundancy

In order to ensure that you can maintain high availability in the face of server failure, you should use which of the following MongoDB feature? Replication

Atomic

Which writes are atomic in MongoDB 4.0? Check all that apply.

  • An update to a single document in a replica set
  • An update to multiple documents in a replica set using transactions
  • An update to a single document in a shared cluster ( updates to single documents in replica sets or sharded clusters are atomic )

Show All Databases

show dbs

Show Current Database

db

Select Or Switch Database

use acme

Drop

db.dropDatabase()

Create Collection

db.createCollection('posts')

Show Collections for Current database

show collections

Insert Row

db.posts.insert({
  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()
  }
])

Get All Rows

db.posts.find()
> db.pets.find()
{ "_id" : ObjectId("58dc747ad3fbf12faaaa1706"), "name" : "Fista", "kind" : "cat", "age" : 2, "colors" : [ "black", "white" ] }
{ "_id" : ObjectId("58dc74e4d3fbf12faaaa1707"), "name" : "Pista", "kind" : "dog", "age" : 4, "colors" : [ "brown" ] }
{ "_id" : ObjectId("58dc74e4d3fbf12faaaa1708"), "name" : "Mista", "kind" : "rat", "age" : 1, "colors" : [ "black", "brown" ] }

Get All Rows Formatted

db.find().pretty()
> db.pets.find().pretty()
{
	"_id" : ObjectId("58dc747ad3fbf12faaaa1706"),
	"name" : "Fista",
	"kind" : "cat",
	"age" : 2,
	"colors" : [
		"black",
		"white"
	]
}
...

Find Rows

db.posts.find({ category: 'News' })
Ondrej Sika <ondrej@ondrejsika.com>

Database

Select Database

use DATABASE_NAME

Example

> use mydb
switched to db mydb

Check selected database

> show dbs
admin  0.000GB
local  0.000GB
test   0.000GB

Create Database

Create database by insert of first document.

switched to db mydb
> db.pets.insert({name: 'Pista', kind: 'dog'})
WriteResult({ "nInserted" : 1 })
> show dbs
admin  0.000GB
local  0.000GB
mydb   0.000GB
test   0.000GB

Drop Database

> db.dropDatabase()
{ "dropped" : "mydb", "ok" : 1 }
> show dbs
admin  0.000GB
local  0.000GB
test   0.000GB

Collection

Create Collection

> use test
switched to db test
> db.createCollection("mycol")
{ "ok" : 1 }
> db.createCollection("cappedcol", {
    capped: true,
    autoIndexID: true,
    size: 1024,
    max: 1
})
{ "ok" : 1 }

List collections

> show collections
mycol
crappedcol

Rename Collection

> db.mycol.renameCollection('newcol')
{ "ok" : 1 }

Drop Collection

> db.mycol.drop()
true

Insert Document

> db.COLLECTION_NAME.insert(DOCUMENT)

Example

db.pets.insert({
    name: 'Fista',
    kind: 'cat',
    age: 2,
    colors: ['black', 'white'],
})
db.pets.insert({
    name: 'Pista',
    kind: 'dog',
    age: 4,
    colors: ['brown'],
})
db.pets.insert({
    name: 'Ben',
    kind: 'dog',
    age: 12,
    colors: ['white'],
})
db.pets.insert({
    name: 'Mista',
    kind: 'rat',
    age: 1,
    colors: ['black', 'brown'],
})

Query Document

Find

Select all documents

> db.COLLECTION_NAME.find()

or

> db.COLLECTION_NAME.find({})

Example

> db.pets.find()
{ "_id" : ObjectId("58dc747ad3fbf12faaaa1706"), "name" : "Fista", "kind" : "cat", "age" : 2, "colors" : [ "black", "white" ] }
{ "_id" : ObjectId("58dc74e4d3fbf12faaaa1707"), "name" : "Pista", "kind" : "dog", "age" : 4, "colors" : [ "brown" ] }
{ "_id" : ObjectId("58dc74e4d3fbf12faaaa1708"), "name" : "Mista", "kind" : "rat", "age" : 1, "colors" : [ "black", "brown" ] }

For pretty formating, use .pretty()

> db.pets.find().pretty()
{
	"_id" : ObjectId("58dc747ad3fbf12faaaa1706"),
	"name" : "Fista",
	"kind" : "cat",
	"age" : 2,
	"colors" : [
		"black",
		"white"
	]
}
...

Operators

Operation Syntax Example SQL
Equality {<key>:<value>} {kind: 'rat'} where kind = 'rat'
Less Than {<key>:{$lt:<value>}} {age: {$lt: 2}} where age < 2
Less Than Equals {<key>:{$lte:<value>}} {age: {$lte: 2}} where age <= 2
Greater Than {<key>:{$gt:<value>}} {age: {$gt: 2}} where age > 2
Greater Than Equals {<key>:{$gte:<value>}} {age: {$gte: 2}} where age >= 2
Not Equals {<key>:{$ne:<value>}} {age: {$ne: 2}} where age != 2
In {<key>:{$in:[<value1>, <value2>, ...]}} {age: {$in: [1, 2, 3]}} where age in (1, 2, 3)

Examples

> db.pets.find({name: 'Pista'})
{ "_id" : ObjectId("58dc7f1fd3fbf12faaaa170a"), "name" : "Pista", "kind" : "dog", "age" : 4, "colors" : [ "brown" ] }
> db.pets.find({kind: 'dog'})
{ "_id" : ObjectId("58dc7f1fd3fbf12faaaa170a"), "name" : "Pista", "kind" : "dog", "age" : 4, "colors" : [ "brown" ] }
{ "_id" : ObjectId("58dc7f1fd3fbf12faaaa170b"), "name" : "Ben", "kind" : "dog", "age" : 12, "colors" : [ "white" ] }
> db.pets.find({colors: 'black'})
{ "_id" : ObjectId("58dc7f1fd3fbf12faaaa170c"), "name" : "Mista", "kind" : "rat", "age" : 1, "colors" : [ "black", "brown" ] }
{ "_id" : ObjectId("58dc7f6cd3fbf12faaaa170d"), "name" : "Fista", "kind" : "cat", "age" : 2, "colors" : [ "black", "white" ] }
> db.pets.find({colors: {$ne: 'black'}})
{ "_id" : ObjectId("58dc7f1fd3fbf12faaaa170a"), "name" : "Pista", "kind" : "dog", "age" : 4, "colors" : [ "brown" ] }
{ "_id" : ObjectId("58dc7f1fd3fbf12faaaa170b"), "name" : "Ben", "kind" : "dog", "age" : 12, "colors" : [ "white" ] }

Columns

db.COLLECTION_NAME.find(QUERY, COLLUMNS)

Example

> db.pets.find({}, {name: 1})
{ "_id" : ObjectId("58dc7f1fd3fbf12faaaa170a"), "name" : "Pista" }
{ "_id" : ObjectId("58dc7f1fd3fbf12faaaa170b"), "name" : "Ben" }
{ "_id" : ObjectId("58dc7f1fd3fbf12faaaa170c"), "name" : "Mista" }
{ "_id" : ObjectId("58dc7f6cd3fbf12faaaa170d"), "name" : "Fista" }
> db.pets.find({}, {name: 1, _id: 0})
{ "name" : "Pista" }
{ "name" : "Ben" }
{ "name" : "Mista" }
{ "name" : "Fista" }
> db.pets.find({}, {_id: 0})
{ "name" : "Pista", "kind" : "dog", "age" : 4, "colors" : [ "brown" ] }
{ "name" : "Ben", "kind" : "dog", "age" : 12, "colors" : [ "white" ] }
{ "name" : "Mista", "kind" : "rat", "age" : 1, "colors" : [ "black", "brown" ] }
{ "name" : "Fista", "kind" : "cat", "age" : 2, "colors" : [ "black", "white" ] }

AND

db.COLLECTION_NAME.find({key1:value1, key2:value2})

Example

> db.pets.find({age: {$gte: 2}, kind: 'dog'})
{ "_id" : ObjectId("58dc74e4d3fbf12faaaa1707"), "name" : "Pista", "kind" : "dog", "age" : 4, "colors" : [ "brown" ] }

OR

db.COLLECTION_NAME.find({$or: [{key1: value1}, {key2:value2}]})

Example

> db.pets.find({$or: [{kind: 'rat'}, {kind: 'cat'}]})
{ "_id" : ObjectId("58dc747ad3fbf12faaaa1706"), "name" : "Fista", "kind" : "cat", "age" : 2, "colors" : [ "black", "white" ] }
{ "_id" : ObjectId("58dc74e4d3fbf12faaaa1708"), "name" : "Mista", "kind" : "rat", "age" : 1, "colors" : [ "black", "brown" ] }

Limit & Offset

> db.pets.find().limit(1)
{ "_id" : ObjectId("58dc7f1fd3fbf12faaaa170a"), "name" : "Pista", "kind" : "dog", "age" : 4, "colors" : [ "brown" ] }
> db.pets.find().skip(1)
{ "_id" : ObjectId("58dc7f1fd3fbf12faaaa170b"), "name" : "Ben", "kind" : "dog", "age" : 12, "colors" : [ "white" ] }
{ "_id" : ObjectId("58dc7f1fd3fbf12faaaa170c"), "name" : "Mista", "kind" : "rat", "age" : 1, "colors" : [ "black", "brown" ] }
{ "_id" : ObjectId("58dc7f6cd3fbf12faaaa170d"), "name" : "Fista", "kind" : "cat", "age" : 2, "colors" : [ "black", "white" ] }
> db.pets.find().skip(1).limit(1)
{ "_id" : ObjectId("58dc7f1fd3fbf12faaaa170b"), "name" : "Ben", "kind" : "dog", "age" : 12, "colors" : [ "white" ] }

Sort

# asc
db.posts.find().sort({ title: 1 }).pretty()
# desc
db.posts.find().sort({ title: -1 }).pretty()
> db.pets.find().sort({name: 1})
{ "_id" : ObjectId("58dc7f1fd3fbf12faaaa170b"), "name" : "Ben", "kind" : "dog", "age" : 12, "colors" : [ "white" ] }
{ "_id" : ObjectId("58dc7f6cd3fbf12faaaa170d"), "name" : "Fista", "kind" : "cat", "age" : 2, "colors" : [ "black", "white" ] }
{ "_id" : ObjectId("58dc7f1fd3fbf12faaaa170c"), "name" : "Mista", "kind" : "rat", "age" : 1, "colors" : [ "black", "brown" ] }
{ "_id" : ObjectId("58dc7f1fd3fbf12faaaa170a"), "name" : "Pista", "kind" : "dog", "age" : 4, "colors" : [ "brown" ] }
> db.pets.find().sort({name: -1} )
{ "_id" : ObjectId("58dc7f1fd3fbf12faaaa170a"), "name" : "Pista", "kind" : "dog", "age" : 4, "colors" : [ "brown" ] }
{ "_id" : ObjectId("58dc7f1fd3fbf12faaaa170c"), "name" : "Mista", "kind" : "rat", "age" : 1, "colors" : [ "black", "brown" ] }
{ "_id" : ObjectId("58dc7f6cd3fbf12faaaa170d"), "name" : "Fista", "kind" : "cat", "age" : 2, "colors" : [ "black", "white" ] }
{ "_id" : ObjectId("58dc7f1fd3fbf12faaaa170b"), "name" : "Ben", "kind" : "dog", "age" : 12, "colors" : [ "white" ] }
> 

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

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

Update Row

db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)

Example

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

Example

> db.pets.update({name: 'Ben'}, {$set: {age: 13}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.pets.find({name: 'Ben'})
{ "_id" : ObjectId("58dc7af7d3fbf12faaaa1709"), "name" : "Ben", "kind" : "dog", "age" : 13, "colors" : [ "white" ] }

By default, MongoDB will update only a single document. To update multiple documents, you need to set a parameter 'multi' to true.

db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA, {multi: true})

Example

> db.pets.update({name: 'Ben'}, {$set: {age: 13}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.pets.find({name: 'Ben'})
{ "_id" : ObjectId("58dc7af7d3fbf12faaaa1709"), "name" : "Ben", "kind" : "dog", "age" : 13, "colors" : [ "white" ] }

Update Specific Field

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

Increment Field ($inc)

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

Rename Field

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

Delete Row

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

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

Find By Element in Array ($elemMatch)

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

Add Index

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

Text Search

text search treats space in { $search : "fact find" } as mutliple values eg "fact find" would be "fact" or "find"

Example

db.sayings.find( { $text : { $search : "fact find" } } )

could return

{ _id: 1, "quote": "fun fact" }
{ _id: 1, "quote": "you must find me" }

Example

finding an exact value that conatins space would look like this.

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

Aggregation

aggregation operators

  • $sum
  • $avg
  • $min
  • $max
  • $push
  • $addToSet
  • $first
  • $last

Example

> db.pets.aggregate([{$group : {_id : "$kind", count: {$sum : 1}}}])
{ "_id" : "cat", "count" : 1 }
{ "_id" : "rat", "count" : 1 }
{ "_id" : "dog", "count" : 2 }
> db.pets.aggregate([{$group : {_id : "$kind", count: {$sum : 1}, age: {$avg: '$age'}}}])
{ "_id" : "cat", "count" : 1, "age" : 2 }
{ "_id" : "rat", "count" : 1, "age" : 1 }
{ "_id" : "dog", "count" : 2, "age" : 8 }

By multiple keys

> db.pets.aggregate([{$group : {_id : {kind: '$kind', age: '$age'}, count: {$sum : 1}}}])
{ "_id" : { "kind" : "cat", "age" : 2 }, "count" : 1 }
{ "_id" : { "kind" : "rat", "age" : 1 }, "count" : 1 }
{ "_id" : { "kind" : "dog", "age" : 12 }, "count" : 1 }
{ "_id" : { "kind" : "dog", "age" : 4 }, "count" : 1 }

addToSet

The $addToSet operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array. $addToSet only ensures that there are no duplicate items added to the set and does not affect existing duplicate elements. $addToSet does not guarantee a particular ordering of elements in the modified set. To specify a <field> in an embedded document or in an array, use dot notation. If you use $addToSet on a field that is absent in the document to update, $addToSet creates the array field with the specified value as its element. If you use $addToSet on a field that is not an array, the operation will fail.

{ $addToSet: { <field1>: <value1>, ... } }

addToSet with each

You can use the $addToSet operator with the $each modifier. The $each modifier allows the $addToSet operator to add multiple values to the array field.

{
  _id: 2,
  item: "cable",
  tags: [ "electronics", "supplies", "accessories" ]
}

db.inventory.update(
   { _id: 2 },
   { $addToSet: { tags: { $each: [ "camera", "electronics", "accessories" ] } } }
 )
 
{
  _id: 2,
  item: "cable",
  tags: [ "electronics", "supplies", "camera", "accessories" ]
}

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