MongoDB Cheat Sheet
MongoDB Cheat Sheet
Table of Content
Helpers
Show Databases
1 show dbs
2 db // prints the current database
Switch Database
1 use <database_name>
Show Collections
1 show collections
Run JavaScript File
1 load("myScript.js")
CRUD
Create
1 db.coll.insertOne({name: "Max"})
2 db.coll.insert([{name: "Max"}, {name:"Alex"}]) // ordered bulk insert
3 db.coll.insert([{name: "Max"}, {name:"Alex"}], {ordered: false}) // unordered bulk
insert
4 db.coll.insert({date: ISODate()})
5 db.coll.insert({name: "Max"}, {"writeConcern": {"w": "majority", "wtimeout":
5000}})
Read
1 db.coll.findOne() // returns a single document
2 db.coll.find() // returns a cursor - show 20 results - "it" to display more
3 db.coll.find().pretty()
4 db.coll.find({name: "Max", age: 32}) // implicit logical "AND".
5 db.coll.find({date: ISODate("2020-09-25T13:57:17.180Z")})
6 db.coll.find({name: "Max", age: 32}).explain("executionStats") // or
"queryPlanner" or "allPlansExecution"
7 db.coll.distinct("name")
8
9 // Count
10 db.coll.count({age: 32}) // estimation based on collection metadata
11 db.coll.estimatedDocumentCount() // estimation based on collection metadata
12 db.coll.countDocuments({age: 32}) // alias for an aggregation pipeline - accurate
count
13
14 // Comparison
15 db.coll.find({"year": {$gt: 1970}})
16 db.coll.find({"year": {$gte: 1970}})
17 db.coll.find({"year": {$lt: 1970}})
18 db.coll.find({"year": {$lte: 1970}})
19 db.coll.find({"year": {$ne: 1970}})
20 db.coll.find({"year": {$in: [1958, 1959]}})
21 db.coll.find({"year": {$nin: [1958, 1959]}})
22
23 // Logical
24 db.coll.find({name:{$not: {$eq: "Max"}}})
25 db.coll.find({$or: [{"year" : 1958}, {"year" : 1959}]})
26 db.coll.find({$nor: [{price: 1.99}, {sale: true}]})
27 db.coll.find({
28 $and: [
29 {$or: [{qty: {$lt :10}}, {qty :{$gt: 50}}]},
30 {$or: [{sale: true}, {price: {$lt: 5 }}]}
31 ]
32 })
33
34 // Element
35 db.coll.find({name: {$exists: true}})
36 db.coll.find({"zipCode": {$type: 2 }})
37 db.coll.find({"zipCode": {$type: "string"}})
38
39 // Aggregation Pipeline
40 db.coll.aggregate([
41 {$match: {status: "A"}},
42 {$group: {_id: "$cust_id", total: {$sum: "$amount"}}},
43 {$sort: {total: -1}}
44 ])
45
46 // Text search with a "text" index
47 db.coll.find({$text: {$search: "cake"}}, {score: {$meta:
"textScore"}}).sort({score: {$meta: "textScore"}})
48
49 // Regex
50 db.coll.find({name: /^Max/}) // regex: starts by letter "M"
51 db.coll.find({name: /^Max$/i}) // regex case insensitive
52
53 // Array
54 db.coll.find({tags: {$all: ["Realm", "Charts"]}})
55 db.coll.find({field: {$size: 2}}) // impossible to index - prefer storing the size of
the array & update it
56 db.coll.find({results: {$elemMatch: {product: "xyz", score: {$gte: 8}}}})
57
58 // Projections
59 db.coll.find({"x": 1}, {"actors": 1}) // actors + _id
60 db.coll.find({"x": 1}, {"actors": 1, "_id": 0}) // actors
61 db.coll.find({"x": 1}, {"actors": 0, "summary": 0}) // all but "actors" and
"summary"
62
63 // Sort, skip, limit
64 db.coll.find({}).sort({"year": 1, "rating": -1}).skip(10).limit(3)
65
66 // Read Concern
67 db.coll.find().readConcern("majority")
• db.collection.find()
• Query and Projection Operators
• BSON types
• Read Concern
Update
1 db.coll.update({"_id": 1}, {"year": 2016}) // WARNING! Replaces the entire
document
2 db.coll.update({"_id": 1}, {$set: {"year": 2016, name: "Max"}})
3 db.coll.update({"_id": 1}, {$unset: {"year": 1}})
4 db.coll.update({"_id": 1}, {$rename: {"year": "date"} })
5 db.coll.update({"_id": 1}, {$inc: {"year": 5}})
6 db.coll.update({"_id": 1}, {$mul: {price: NumberDecimal("1.25"), qty: 2}})
7 db.coll.update({"_id": 1}, {$min: {"imdb": 5}})
8 db.coll.update({"_id": 1}, {$max: {"imdb": 8}})
9 db.coll.update({"_id": 1}, {$currentDate: {"lastModified": true}})
10 db.coll.update({"_id": 1}, {$currentDate: {"lastModified": {$type:
"timestamp"}}})
11
12 // Array
13 db.coll.update({"_id": 1}, {$push :{"array": 1}})
14 db.coll.update({"_id": 1}, {$pull :{"array": 1}})
15 db.coll.update({"_id": 1}, {$addToSet :{"array": 2}})
16 db.coll.update({"_id": 1}, {$pop: {"array": 1}}) // last element
17 db.coll.update({"_id": 1}, {$pop: {"array": -1}}) // first element
18 db.coll.update({"_id": 1}, {$pullAll: {"array" :[3, 4, 5]}})
19 db.coll.update({"_id": 1}, {$push: {scores: {$each: [90, 92, 85]}}})
20 db.coll.updateOne({"_id": 1, "grades": 80}, {$set: {"grades.$": 82}})
21 db.coll.updateMany({}, {$inc: {"grades.$[]": 10}})
22 db.coll.update({}, {$set: {"grades.$[element]": 100}}, {multi: true, arrayFilters:
[{"element": {$gte: 100}}]})
23
24 // Update many
25 db.coll.update({"year": 1999}, {$set: {"decade": "90's"}}, {"multi":true})
26 db.coll.updateMany({"year": 1999}, {$set: {"decade": "90's"}})
27
28 // FindOneAndUpdate
29 db.coll.findOneAndUpdate({"name": "Max"}, {$inc: {"points": 5}},
{returnNewDocument: true})
30
31 // Upsert
32 db.coll.update({"_id": 1}, {$set: {item: "apple"}, $setOnInsert: {defaultQty:
100}}, {upsert: true})
33
34 // Replace
35 db.coll.replaceOne({"name": "Max"}, {"firstname": "Maxime", "surname":
"Beugnet"})
36
37 // Save
38 db.coll.save({"item": "book", "qty": 40})
39
40 // Write concern
41 db.coll.update({}, {$set: {"x": 1}}, {"writeConcern": {"w": "majority",
"wtimeout": 5000}})
Delete
1 db.coll.remove({name: "Max"})
2 db.coll.remove({name: "Max"}, {justOne: true})
3 db.coll.remove({}) // WARNING! Deletes all the docs but not the collection itself
and its index definitions
4 db.coll.remove({name: "Max"}, {"writeConcern": {"w": "majority", "wtimeout":
5000}})
5 db.coll.findOneAndDelete({"name": "Max"})
Indexes
List Indexes
1 db.coll.getIndexes()
2 db.coll.getIndexKeys()
Create Indexes
1 // Index Types
2 db.coll.createIndex({"name": 1}) // single field index
3 db.coll.createIndex({"name": 1, "date": 1}) // compound index
4 db.coll.createIndex({foo: "text", bar: "text"}) // text index
5 db.coll.createIndex({"$**": "text"}) // wildcard text index
6 db.coll.createIndex({"userMetadata.$**": 1}) // wildcard index
7 db.coll.createIndex({"loc": "2d"}) // 2d index
8 db.coll.createIndex({"loc": "2dsphere"}) // 2dsphere index
9 db.coll.createIndex({"_id": "hashed"}) // hashed index
10
11 // Index Options
12 db.coll.createIndex({"lastModifiedDate": 1}, {expireAfterSeconds: 3600}) // TTL
index
13 db.coll.createIndex({"name": 1}, {unique: true})
14 db.coll.createIndex({"name": 1}, {partialFilterExpression: {age: {$gt: 18}}}) //
partial index
15 db.coll.createIndex({"name": 1}, {collation: {locale: 'en', strength: 1}}) // case
insensitive index with strength = 1 or 2
16 db.coll.createIndex({"name": 1 }, {sparse: true})
Drop Indexes
1 db.coll.dropIndex("name_1")
Hide/Unhide Indexes
1 db.coll.hideIndex("name_1")
2 db.coll.unhideIndex("name_1")
• Indexes documentation
Handy commands
1 use admin
2 db.createUser({"user": "root", "pwd": passwordPrompt(), "roles": ["root"]})
3 db.dropUser("root")
4 db.auth( "user", passwordPrompt() )
5
6 use test
7 db.getSiblingDB("dbname")
8 db.currentOp()
9 db.killOp(123) // opid
10
11 db.fsyncLock()
12 db.fsyncUnlock()
13
14 db.getCollectionNames()
15 db.getCollectionInfos()
16 db.printCollectionStats()
17 db.stats()
18
19 db.getReplicationInfo()
20 db.printReplicationInfo()
21 db.isMaster()
22 db.hostInfo()
23 db.printShardingStatus()
24 db.shutdownServer()
25 db.serverStatus()
26
27 db.setSlaveOk()
28 db.getSlaveOk()
29
30 db.getProfilingLevel()
31 db.getProfilingStatus()
32 db.setProfilingLevel(1, 200) // 0 == OFF, 1 == ON with slowms, 2 == ON
33
34 db.enableFreeMonitoring()
35 db.disableFreeMonitoring()
36 db.getFreeMonitoringStatus()
37
38 db.createView("viewName", "sourceColl", [{$project:{department: 1}}])
Change Streams
1 watchCursor = db.coll.watch( [ { $match : {"operationType" : "insert" } } ] )
2
3 while (!watchCursor.isExhausted()){
4 if (watchCursor.hasNext()){
5 print(tojson(watchCursor.next()));
6 }
7 }
Replica Set
1 rs.status()
2 rs.initiate({"_id": "replicaTest",
3 members: [
4 { _id: 0, host: "127.0.0.1:27017" },
5 { _id: 1, host: "127.0.0.1:27018" },
6 { _id: 2, host: "127.0.0.1:27019", arbiterOnly:true }]
7 })
8 rs.add("mongodbd1.example.net:27017")
9 rs.addArb("mongodbd2.example.net:27017")
10 rs.remove("mongodbd1.example.net:27017")
11 rs.conf()
12 rs.isMaster()
13 rs.printReplicationInfo()
14 rs.printSlaveReplicationInfo()
15 rs.reconfig(<valid_conf>)
16 rs.slaveOk()
17 rs.stepDown(20, 5) // (stepDownSecs, secondaryCatchUpPeriodSecs)
Sharded Cluster
1 sh.status()
2 sh.addShard("rs1/mongodbd1.example.net:27017")
3 sh.shardCollection("mydb.coll", {zipcode: 1})
4
5 sh.moveChunk("mydb.coll", { zipcode: "53187" }, "shard0019")
6 sh.splitAt("mydb.coll", {x: 70})
7 sh.splitFind("mydb.coll", {x: 70})
8 sh.disableAutoSplit()
9 sh.enableAutoSplit()
10
11 sh.startBalancer()
12 sh.stopBalancer()
13 sh.disableBalancing("mydb.coll")
14 sh.enableBalancing("mydb.coll")
15 sh.getBalancerState()
16 sh.setBalancerState(true/false)
17 sh.isBalancerRunning()
18
19 sh.addTagRange("mydb.coll", {state: "NY", zip: MinKey }, { state: "NY", zip:
MaxKey }, "NY")
20 sh.removeTagRange("mydb.coll", {state: "NY", zip: MinKey }, { state: "NY", zip:
MaxKey }, "NY")
21 sh.addShardTag("shard0000", "NYC")
22 sh.removeShardTag("shard0000", "NYC")
23
24 sh.addShardToZone("shard0000", "JFK")
25 sh.removeShardFromZone("shard0000", "NYC")
26 sh.removeRangeFromZone("mydb.coll", {a: 1, b: 1}, {a: 10, b: 10})
copy code