Explore Developer Center's New Chatbot! MongoDB AI Chatbot can be accessed at the top of your navigation to answer all your MongoDB questions.

Join us at AWS re:Invent 2024! Learn how to use MongoDB for AI use cases.
MongoDB Developer
MongoDB
plus
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Productschevron-right
MongoDBchevron-right

MongoDB Cheat Sheet

Maxime Beugnet5 min read • Published Jan 31, 2022 • Updated Sep 29, 2023
MongoDB
Facebook Icontwitter iconlinkedin icon
Rate this quickstart
star-empty
star-empty
star-empty
star-empty
star-empty
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!
  • Get a free MongoDB cluster in MongoDB Atlas.
  • Follow a course in MongoDB University.

Updates

  • September 2023: Updated for MongoDB 7.0.

Table of Contents

Connect via

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

Helpers

Show Databases

1show dbs
2db // prints the current database

Switch Database

1use <database_name>

Show Collections

1show collections

Run JavaScript File

1load("myScript.js")

CRUD

Create

1db.coll.insertOne({name: "Max"})
2db.coll.insertMany([{name: "Max"}, {name:"Alex"}]) // ordered bulk insert
3db.coll.insertMany([{name: "Max"}, {name:"Alex"}], {ordered: false}) // unordered bulk insert
4db.coll.insertOne({date: ISODate()})
5db.coll.insertOne({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.countDocuments({age: 32}) // alias for an aggregation pipeline - accurate count
11db.coll.estimatedDocumentCount() // estimation based on collection metadata
12
13// Comparison
14db.coll.find({"year": {$gt: 1970}})
15db.coll.find({"year": {$gte: 1970}})
16db.coll.find({"year": {$lt: 1970}})
17db.coll.find({"year": {$lte: 1970}})
18db.coll.find({"year": {$ne: 1970}})
19db.coll.find({"year": {$in: [1958, 1959]}})
20db.coll.find({"year": {$nin: [1958, 1959]}})
21
22// Logical
23db.coll.find({name:{$not: {$eq: "Max"}}})
24db.coll.find({$or: [{"year" : 1958}, {"year" : 1959}]})
25db.coll.find({$nor: [{price: 1.99}, {sale: true}]})
26db.coll.find({
27 $and: [
28 {$or: [{qty: {$lt :10}}, {qty :{$gt: 50}}]},
29 {$or: [{sale: true}, {price: {$lt: 5 }}]}
30 ]
31})
32
33// Element
34db.coll.find({name: {$exists: true}})
35db.coll.find({"zipCode": {$type: 2 }})
36db.coll.find({"zipCode": {$type: "string"}})
37
38// Aggregation Pipeline
39db.coll.aggregate([
40 {$match: {status: "A"}},
41 {$group: {_id: "$cust_id", total: {$sum: "$amount"}}},
42 {$sort: {total: -1}}
43])
44
45// Text search with a "text" index
46db.coll.find({$text: {$search: "cake"}}, {score: {$meta: "textScore"}}).sort({score: {$meta: "textScore"}})
47
48// Regex
49db.coll.find({name: /^Max/}) // regex: starts by letter "M"
50db.coll.find({name: /^Max$/i}) // regex case insensitive
51
52// Array
53db.coll.find({tags: {$all: ["Realm", "Charts"]}})
54db.coll.find({field: {$size: 2}}) // impossible to index - prefer storing the size of the array & update it
55db.coll.find({results: {$elemMatch: {product: "xyz", score: {$gte: 8}}}})
56
57// Projections
58db.coll.find({"x": 1}, {"actors": 1}) // actors + _id
59db.coll.find({"x": 1}, {"actors": 1, "_id": 0}) // actors
60db.coll.find({"x": 1}, {"actors": 0, "summary": 0}) // all but "actors" and "summary"
61
62// Sort, skip, limit
63db.coll.find({}).sort({"year": 1, "rating": -1}).skip(10).limit(3)
64
65// Read Concern
66db.coll.find().readConcern("majority")

Update

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

Delete

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

Databases and Collections

Drop

1db.coll.drop() // removes the collection and its index definitions
2db.dropDatabase() // double check that you are *NOT* on the PROD cluster... :-)

Create Collection

1// Create collection with a $jsonschema
2db.createCollection("contacts", {
3 validator: {$jsonSchema: {
4 bsonType: "object",
5 required: ["phone"],
6 properties: {
7 phone: {
8 bsonType: "string",
9 description: "must be a string and is required"
10 },
11 email: {
12 bsonType: "string",
13 pattern: "@mongodb\.com$",
14 description: "must be a string and match the regular expression pattern"
15 },
16 status: {
17 enum: [ "Unknown", "Incomplete" ],
18 description: "can only be one of the enum values"
19 }
20 }
21 }}
22})

Other Collection Functions

1db.coll.stats()
2db.coll.storageSize()
3db.coll.totalIndexSize()
4db.coll.totalSize()
5db.coll.validate({full: true})
6db.coll.renameCollection("new_coll", true) // 2nd parameter to drop the target collection if exists

Indexes

List Indexes

1db.coll.getIndexes()
2db.coll.getIndexKeys()

Create Indexes

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

Drop Indexes

1db.coll.dropIndex("name_1")

Hide/Unhide Indexes

1db.coll.hideIndex("name_1")
2db.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.hello()
22db.hostInfo()
23
24db.shutdownServer()
25db.serverStatus()
26
27db.getProfilingStatus()
28db.setProfilingLevel(1, 200) // 0 == OFF, 1 == ON with slowms, 2 == ON
29
30db.enableFreeMonitoring()
31db.disableFreeMonitoring()
32db.getFreeMonitoringStatus()
33
34db.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": "RS1",
3 members: [
4 { _id: 0, host: "mongodb1.net:27017" },
5 { _id: 1, host: "mongodb2.net:27017" },
6 { _id: 2, host: "mongodb3.net:27017" }]
7})
8rs.add("mongodb4.net:27017")
9rs.addArb("mongodb5.net:27017")
10rs.remove("mongodb1.net:27017")
11rs.conf()
12rs.hello()
13rs.printReplicationInfo()
14rs.printSecondaryReplicationInfo()
15rs.reconfig(config)
16rs.reconfigForPSASet(memberIndex, config, { options } )
17db.getMongo().setReadPref('secondaryPreferred')
18rs.stepDown(20, 5) // (stepDownSecs, secondaryCatchUpPeriodSecs)

Sharded Cluster

1db.printShardingStatus()
2
3sh.status()
4sh.addShard("rs1/mongodb1.example.net:27017")
5sh.shardCollection("mydb.coll", {zipcode: 1})
6
7sh.moveChunk("mydb.coll", { zipcode: "53187" }, "shard0019")
8sh.splitAt("mydb.coll", {x: 70})
9sh.splitFind("mydb.coll", {x: 70})
10
11sh.startBalancer()
12sh.stopBalancer()
13sh.disableBalancing("mydb.coll")
14sh.enableBalancing("mydb.coll")
15sh.getBalancerState()
16sh.setBalancerState(true/false)
17sh.isBalancerRunning()
18
19sh.startAutoMerger()
20sh.stopAutoMerger()
21sh.enableAutoMerger()
22sh.disableAutoMerger()
23
24sh.updateZoneKeyRange("mydb.coll", {state: "NY", zip: MinKey }, { state: "NY", zip: MaxKey }, "NY")
25sh.removeRangeFromZone("mydb.coll", {state: "NY", zip: MinKey }, { state: "NY", zip: MaxKey })
26sh.addShardToZone("shard0000", "NYC")
27sh.removeShardFromZone("shard0000", "NYC")

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.

Facebook Icontwitter iconlinkedin icon
Rate this quickstart
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Code Example

GroupUs


Jul 07, 2022 | 1 min read
Article

Paginations 1.0: Time Series Collections in five minutes


May 19, 2022 | 4 min read
Tutorial

Modernizing RDBMS Schemas With a MongoDB Document Model


Mar 06, 2024 | 6 min read
Article

Securing MongoDB with TLS


May 09, 2022 | 4 min read
Table of Contents