Learn, develop, and innovate from anywhere. Join us for our MongoDB .Live series.
HomeLearnQuickstart

MongoDB Cheat Sheet

Published: Sep 30, 2020

  • MongoDB
  • University

By Maxime Beugnet

Share

First steps in the MongoDB World? This cheat sheet is filled with some handy tips, commands, and quick references to get you connected and CRUD'ing in no time!

#Connect MongoDB Shell

1mongo # connects to mongodb://127.0.0.1:27017 by default
2mongo --host <host> --port <port> -u <user> -p <pwd> # omit the password if you want a prompt
3mongo "mongodb://192.168.1.1:27017"
4mongo "mongodb+srv://cluster-name.abcde.mongodb.net/<dbname>" --username <username> # MongoDB Atlas

#Helpers

1show dbs
2use <database_name>
3db // prints the current database
4show collections
5load(myScript.js)

#CRUD

#Create

1db.coll.insertOne({name: "Max"})
2db.coll.insert([{name: "Max"}, {name:"Alex"}]) // ordered bulk insert
3db.coll.insert([{name: "Max"}, {name:"Alex"}], {ordered: false}) // unordered bulk insert
4db.coll.insert({date: ISODate()})
5db.coll.insert({name: "Max"}, {"writeConcern": {"w": "majority", "wtimeout": 5000}})

#Read

1db.coll.findOne() // returns a single document
2db.coll.find() // returns a cursor - show 20 results - "it" to display more
3db.coll.find().pretty()
4db.coll.find({name: "Max", age: 32}) // implicit logical "AND".
5db.coll.find({date: ISODate("2020-09-25T13:57:17.180Z")})
6db.coll.find({name: "Max", age: 32}).explain("executionStats") // or "queryPlanner" or "allPlansExecution"
7db.coll.distinct("name")
8
9// Count
10db.coll.count({age: 32}) // estimation based on collection metadata
11db.coll.estimatedDocumentCount() // estimation based on collection metadata
12db.coll.countDocuments({age: 32}) // alias for an aggregation pipeline - accurate count
13
14// Comparison
15db.coll.find({"year": {$gt: 1970}})
16db.coll.find({"year": {$gte: 1970}})
17db.coll.find({"year": {$lt: 1970}})
18db.coll.find({"year": {$lte: 1970}})
19db.coll.find({"year": {$ne: 1970}})
20db.coll.find({"year": {$in: [1958, 1959]}})
21db.coll.find({"year": {$nin: [1958, 1959]}})
22
23// Logical
24db.coll.find({name:{$not: {$eq: "Max"}}})
25db.coll.find({$or: [{"year" : 1958}, {"year" : 1959}]})
26db.coll.find({$nor: [{price: 1.99}, {sale: true}]})
27db.coll.find({
28 $and: [
29 {$or: [{qty: {$lt :10}}, {qty :{$gt: 50}}]},
30 {$or: [{sale: true}, {price: {$lt: 5 }}]}
31 ]
32})
33
34// Element
35db.coll.find({name: {$exists: true}})
36db.coll.find({"zipCode": {$type: 2 }})
37db.coll.find({"zipCode": {$type: "string"}})
38
39// Aggregation Pipeline
40db.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
47db.coll.find({$text: {$search: "cake"}}, {score: {$meta: "textScore"}}).sort({score: {$meta: "textScore"}})
48
49// Regex
50db.coll.find({name: /^Max/}) // regex: starts by letter "M"
51db.coll.find({name: /^Max$/i}) // regex case insensitive
52
53// Array
54db.coll.find({tags: {$all: ["Realm", "Charts"]}})
55db.coll.find({field: {$size: 2}}) // impossible to index - prefer storing the size of the array & update it
56db.coll.find({results: {$elemMatch: {product: "xyz", score: {$gte: 8}}}})
57
58// Projections
59db.coll.find({"x": 1}, {"actors": 1}) // actors + _id
60db.coll.find({"x": 1}, {"actors": 1, "_id": 0}) // actors
61db.coll.find({"x": 1}, {"actors": 0, "summary": 0}) // all but "actors" and "summary"
62
63// Sort, skip, limit
64db.coll.find({}).sort({"year": 1, "rating": -1}).skip(10).limit(3)
65
66// Read Concern
67db.coll.find().readConcern("majority")

#Update

1db.coll.update({"_id": 1}, {"year": 2016}) // WARNING! Replaces the entire document
2db.coll.update({"_id": 1}, {$set: {"year": 2016, name: "Max"}})
3db.coll.update({"_id": 1}, {$unset: {"year": 1}})
4db.coll.update({"_id": 1}, {$rename: {"year": "date"} })
5db.coll.update({"_id": 1}, {$inc: {"year": 5}})
6db.coll.update({"_id": 1}, {$mul: {price: NumberDecimal("1.25"), qty: 2}})
7db.coll.update({"_id": 1}, {$min: {"imdb": 5}})
8db.coll.update({"_id": 1}, {$max: {"imdb": 8}})
9db.coll.update({"_id": 1}, {$currentDate: {"lastModified": true}})
10db.coll.update({"_id": 1}, {$currentDate: {"lastModified": {$type: "timestamp"}}})
11
12// Array
13db.coll.update({"_id": 1}, {$push :{"array": 1}})
14db.coll.update({"_id": 1}, {$pull :{"array": 1}})
15db.coll.update({"_id": 1}, {$addToSet :{"array": 2}})
16db.coll.update({"_id": 1}, {$pop: {"array": 1}}) // last element
17db.coll.update({"_id": 1}, {$pop: {"array": -1}}) // first element
18db.coll.update({"_id": 1}, {$pullAll: {"array" :[3, 4, 5]}})
19db.coll.update({"_id": 1}, {$push: {scores: {$each: [90, 92, 85]}}})
20db.coll.updateOne({"_id": 1, "grades": 80}, {$set: {"grades.$": 82}})
21db.coll.updateMany({}, {$inc: {"grades.$[]": 10}})
22db.coll.update({}, {$set: {"grades.$[element]": 100}}, {multi: true, arrayFilters: [{"element": {$gte: 100}}]})
23
24// Update many
25db.coll.update({"year": 1999}, {$set: {"decade": "90's"}}, {"multi":true})
26db.coll.updateMany({"year": 1999}, {$set: {"decade": "90's"}})
27
28// FindOneAndUpdate
29db.coll.findOneAndUpdate({"name": "Max"}, {$inc: {"points": 5}}, {returnNewDocument: true})
30
31// Upsert
32db.coll.update({"_id": 1}, {$set: {item: "apple"}, $setOnInsert: {defaultQty: 100}}, {upsert: true})
33
34// Replace
35db.coll.replaceOne({"name": "Max"}, {"firstname": "Maxime", "surname": "Beugnet"})
36
37// Save
38db.coll.save({"item": "book", "qty": 40})
39
40// Write concern
41db.coll.update({}, {$set: {"x": 1}}, {"writeConcern": {"w": "majority", "wtimeout": 5000}})

#Delete

1db.coll.remove({name: "Max"})
2db.coll.remove({name: "Max"}, {justOne: true})
3db.coll.remove({}) // WARNING! Deletes all the docs but not the collection itself and its index definitions
4db.coll.remove({name: "Max"}, {"writeConcern": {"w": "majority", "wtimeout": 5000}})
5db.coll.findOneAndDelete({"name": "Max"})

#Databases and Collections

1db.coll.drop() // removes the collection and its index definitions
2db.dropDatabase() // double check that you are *NOT* on the PROD cluster... :-)
3
4// Create collection with a $jsonschema
5db.createCollection("contacts", {
6 validator: {$jsonSchema: {
7 bsonType: "object",
8 required: ["phone"],
9 properties: {
10 phone: {
11 bsonType: "string",
12 description: "must be a string and is required"
13 },
14 email: {
15 bsonType: "string",
16 pattern: "@mongodb\.com$",
17 description: "must be a string and match the regular expression pattern"
18 },
19 status: {
20 enum: [ "Unknown", "Incomplete" ],
21 description: "can only be one of the enum values"
22 }
23 }
24 }}
25})
26
27db.coll.stats()
28db.coll.storageSize()
29db.coll.totalIndexSize()
30db.coll.totalSize()
31db.coll.validate({full: true})
32db.coll.renameCollection("new_coll", true) // 2nd parameter to drop the target collection if exists

#Indexes

1db.coll.getIndexes()
2db.coll.getIndexKeys()
3
4// Index Types
5db.coll.createIndex({"name": 1}) // single field index
6db.coll.createIndex({"name": 1, "date": 1}) // compound index
7db.coll.createIndex({foo: "text", bar: "text"}) // text index
8db.coll.createIndex({"$**": "text"}) // wildcard text index
9db.coll.createIndex({"userMetadata.$**": 1}) // wildcard index
10db.coll.createIndex({"loc": "2d"}) // 2d index
11db.coll.createIndex({"loc": "2dsphere"}) // 2dsphere index
12db.coll.createIndex({"_id": "hashed"}) // hashed index
13
14// Index Options
15db.coll.createIndex({"lastModifiedDate": 1}, {expireAfterSeconds: 3600}) // TTL index
16db.coll.createIndex({"name": 1}, {unique: true})
17db.coll.createIndex({"name": 1}, {partialFilterExpression: {age: {$gt: 18}}}) // partial index
18db.coll.createIndex({"name": 1}, {collation: {locale: 'en', strength: 1}}) // case insensitive index with strength = 1 or 2
19db.coll.createIndex({"name": 1 }, {sparse: true})
20
21db.coll.dropIndex("name_1")
22
23db.coll.hideIndex("name_1")
24db.coll.unhideIndex("name_1")

#Handy commands

1use admin
2db.createUser({"user": "root", "pwd": passwordPrompt(), "roles": ["root"]})
3db.dropUser("root")
4db.auth( "user", passwordPrompt() )
5
6use test
7db.getSiblingDB("dbname")
8db.currentOp()
9db.killOp(123) // opid
10
11db.fsyncLock()
12db.fsyncUnlock()
13
14db.getCollectionNames()
15db.getCollectionInfos()
16db.printCollectionStats()
17db.stats()
18
19db.getReplicationInfo()
20db.printReplicationInfo()
21db.isMaster()
22db.hostInfo()
23db.printShardingStatus()
24db.shutdownServer()
25db.serverStatus()
26
27db.setSlaveOk()
28db.getSlaveOk()
29
30db.getProfilingLevel()
31db.getProfilingStatus()
32db.setProfilingLevel(1, 200) // 0 == OFF, 1 == ON with slowms, 2 == ON
33
34db.enableFreeMonitoring()
35db.disableFreeMonitoring()
36db.getFreeMonitoringStatus()
37
38db.createView("viewName", "sourceColl", [{$project:{department: 1}}])

#Change Streams

1watchCursor = db.coll.watch( [ { $match : {"operationType" : "insert" } } ] )
2
3while (!watchCursor.isExhausted()){
4 if (watchCursor.hasNext()){
5 print(tojson(watchCursor.next()));
6 }
7}

#Replica Set

1rs.status()
2rs.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})
8rs.add("mongodbd1.example.net:27017")
9rs.addArb("mongodbd2.example.net:27017")
10rs.remove("mongodbd1.example.net:27017")
11rs.conf()
12rs.isMaster()
13rs.printReplicationInfo()
14rs.printSlaveReplicationInfo()
15rs.reconfig(<valid_conf>)
16rs.slaveOk()
17rs.stepDown(20, 5) // (stepDownSecs, secondaryCatchUpPeriodSecs)

#Sharded Cluster

1sh.status()
2sh.addShard("rs1/mongodbd1.example.net:27017")
3sh.shardCollection("mydb.coll", {zipcode: 1})
4
5sh.moveChunk("mydb.coll", { zipcode: "53187" }, "shard0019")
6sh.splitAt("mydb.coll", {x: 70})
7sh.splitFind("mydb.coll", {x: 70})
8sh.disableAutoSplit()
9sh.enableAutoSplit()
10
11sh.startBalancer()
12sh.stopBalancer()
13sh.disableBalancing("mydb.coll")
14sh.enableBalancing("mydb.coll")
15sh.getBalancerState()
16sh.setBalancerState(true/false)
17sh.isBalancerRunning()
18
19sh.addTagRange("mydb.coll", {state: "NY", zip: MinKey }, { state: "NY", zip: MaxKey }, "NY")
20sh.removeTagRange("mydb.coll", {state: "NY", zip: MinKey }, { state: "NY", zip: MaxKey }, "NY")
21sh.addShardTag("shard0000", "NYC")
22sh.removeShardTag("shard0000", "NYC")
23
24sh.addShardToZone("shard0000", "JFK")
25sh.removeShardFromZone("shard0000", "NYC")
26sh.removeRangeFromZone("mydb.coll", {a: 1, b: 1}, {a: 10, b: 10})

#Wrap-up

I hope you liked my little but - hopefully - helpful cheat sheet. Of course, this list isn't exhaustive at all. There are a lot more commands but I'm sure you will find them in the MongoDB documentation.

If you feel like I forgot a critical command in this list, please send me a tweet and I will make sure to fix it.

Check out our free courses on MongoDB University if you are not too sure what some of the above commands are doing.

If you have questions, please head to our developer community website where the MongoDB engineers and the MongoDB community will help you build your next big idea with MongoDB.

MongoDB Icon
  • Developer Hub
  • Documentation
  • University
  • Community Forums

© MongoDB, Inc.