- MongoDB Cheet Sheet
- Show All Databases
- Show Current Database
- Select Or Switch Database
- Drop
- Create Collection
- Show Collections for Current database
- Insert Row
- Insert Multiple Rows
- Get All Rows
- Get All Rows Formatted
- Find Rows
- Database
- Collection
- Insert Document
- Query Document
- Count Rows
- Limit Rows
- Chaining
- Foreach
- Find One Row
- Find Specific Fields
- Update Row
- Update Specific Field
- Increment Field ($inc)
- Rename Field
- Delete Row
- Sub-Documents
- Find By Element in Array ($elemMatch)
- Add Index
- Text Search
- Greater & Less Than
- Aggregation
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.
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
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 dbs
db
use acme
db.dropDatabase()
db.createCollection('posts')
show collections
db.posts.insert({
title: 'Post One',
body: 'Body of post one',
category: 'News',
tags: ['news', 'events'],
user: {
name: 'John Doe',
status: 'author'
},
date: Date()
})
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()
}
])
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" ] }
db.find().pretty()
> db.pets.find().pretty()
{
"_id" : ObjectId("58dc747ad3fbf12faaaa1706"),
"name" : "Fista",
"kind" : "cat",
"age" : 2,
"colors" : [
"black",
"white"
]
}
...
db.posts.find({ category: 'News' })
Ondrej Sika <ondrej@ondrejsika.com>
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 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
> db.dropDatabase()
{ "dropped" : "mydb", "ok" : 1 }
> show dbs
admin 0.000GB
local 0.000GB
test 0.000GB
> use test
switched to db test
> db.createCollection("mycol")
{ "ok" : 1 }
> db.createCollection("cappedcol", {
capped: true,
autoIndexID: true,
size: 1024,
max: 1
})
{ "ok" : 1 }
> show collections
mycol
crappedcol
> db.mycol.renameCollection('newcol')
{ "ok" : 1 }
> db.mycol.drop()
true
> 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'],
})
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"
]
}
...
- List of all operators - see docs - https://docs.mongodb.com/manual/reference/operator/query/
| 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" ] }
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" ] }
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" ] }
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" ] }
> 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" ] }
# 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" ] }
>
db.posts.find().count()
db.posts.find({ category: 'news' }).count()
db.posts.find().limit(2).pretty()
db.posts.find().limit(2).sort({ title: 1 }).pretty()
db.posts.find().forEach(function(doc) {
print("Blog Post: " + doc.title)
})
db.posts.findOne({ category: 'News' })
db.posts.find({ title: 'Post One' }, {
title: 1,
author: 1
})
db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)
db.posts.update({ title: 'Post Two' },
{
title: 'Post Two',
body: 'New body for post 2',
date: Date()
},
{
upsert: true
})
> 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})
> 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" ] }
db.posts.update({ title: 'Post Two' },
{
$set: {
body: 'Body for post 2',
category: 'Technology'
}
})
db.posts.update({ title: 'Post Two' },
{
$inc: {
likes: 5
}
})
db.posts.update({ title: 'Post Two' },
{
$rename: {
likes: 'views'
}
})
db.posts.remove({ title: 'Post Four' })
db.posts.update({ title: 'Post One' },
{
$set: {
comments: [
{
body: 'Comment One',
user: 'Mary Williams',
date: Date()
},
{
body: 'Comment Two',
user: 'Harry White',
date: Date()
}
]
}
})
db.posts.find({
comments: {
$elemMatch: {
user: 'Mary Williams'
}
}
}
)
db.posts.createIndex({ title: 'text' })
text search treats space in { $search : "fact find" } as mutliple values eg "fact find" would be "fact" or "find"
db.sayings.find( { $text : { $search : "fact find" } } )
could return
{ _id: 1, "quote": "fun fact" }
{ _id: 1, "quote": "you must find me" }
finding an exact value that conatins space would look like this.
db.posts.find({
$text: {
$search: "\"Post O\""
}
})
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 operators
$sum$avg$min$max$push$addToSet$first$last
> 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 }
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>, ... } }
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" ]
}