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

 

Basic Commands

These basic help commands are available in the MongoDB Shell.

Keyword Description
mongosh Open a connection to your local MongoDB instance. All other commands will be run within this mongosh connection.
db.help() Show help for database methods.

db.<collection>.help()

db.users.help()

Show help on collection methods. The <collection> can be the name of an existing collection or a non-existing collection. Shows help on methods related to the users collection.

show dbs Print a list of all databases on the server.
use <db> Switch the current database to <db>. The Mongo shell variable db is set to the current database.
show collections Print a list of all collections for the current database.
show users Print a list of users for the current database.
show roles Print a list of all roles, both user-deīŦned and built-in, for the current database.
show profile Print the īŦve most recent operations that took 1 millisecond or more on databases with proīŦling enabled.
show databases Print a list of all existing databases available to the current user.
exit Exit the mongosh session.
Create Operations

Create or insert operations and add new documents to a collection. If the collection does not exist, create operations also create the collection.

Keyword Description

db.collection.insertOne()

db.users.insertOne({name: “Chris”})

Inserts a single document into a collection. Add a new document with the name of Chris into the users collection

db.collection.insertMany()

db.users.insertMany({age:”24â€ŗ},{age:”38â€ŗ} )

Inserts multiple documents into a collection. Add two new documents with the ages of 24 and 38 into the users collection

Read Operations

Read operations retrieve documents from a collection; i.e. query a collection for documents.

Keyword Description

db.collection.find()

db.collection.find(<filterobjec t>) db.users.find({place: “NYC”})

Selects documents in a collection or view and returns a cursor to the selected documents. Returns all users. Find all documents that match the īŦlter object Returns all users with the place NYC.

db.collection.find({<field>:1,< field>:1})

db.users.find({status:1,item:1})

db.collection.find({<field>:1,< field>:0, _id:0})  

db.users.find({status:1,item:1,_id:0} )

Returns all documents that match the query after you explicitly include several īŦelds by setting the <īŦeld> to 1 in the projection document. Returns matching documents only from state īŦeld, item īŦeld, and, by default, the _id īŦeld.

Returns all documents that match the query and removes the _id īŦeld from the results by setting it to 0 in the projection. Returns matching documents only from state īŦeld and item īŦeld. Does not return the _id īŦeld.

Update Operations

Update operations modify existing documents in a collection.

Keyword Description

db.collection.updateOne()

db.users.updateOne({age: 25 },{$set:{age:32}})

Updates a single document within the collection based on the īŦlter. Updates all users from the age of 25 to 32.

db.collection.updateMany()

db.users.updateMany({age:27},{$inc:{age:3}})

Updates a single document within the collection based on the īŦlter. Updates all users with an age of 27 with an increase of 3.

db.collection.replaceOne()

db.users.replaceOne({name:Kris},{name:Chris})

Replaces a single document within the collection based on the īŦlter. Replace the īŦrst user with the name Kris with a document that has the name Chris in its name īŦeld.
Delete Operations

Delete operations remove documents from a collection.

Keyword Description

db.collection.deleteOne()

db.users.deleteOne({age:37})

Removes a single document from a collection. Deletes the īŦrst user with the age of 37.

db.collection.deleteMany()

db.users.deleteMany({age:{$lt:18})

Removes all documents that match the īŦlter from a collection. Deletes all users aged less than 18.
Comparison Query Operators

Use the following inside an īŦlter object to make complex queries

Keyword Description

$eq

db.users.find({ system:{$eq:”macOS”}})

Matches values that are equal to a speciīŦed value. Finds all users with the operating system macOS.

$gt

db.users.deleteMany({age:{$gt:99}})

Matches values that are greater than a speciīŦed value. Deletes all users with an age greater than 99.

$gte

db.users.updateMany({ age”: {$gte:21 },{access: “valid”})

Matches values that are greater than or equal to a speciīŦed value. Updates all access to “valid” for all users with an age greater than or equal to 21.

$in

db.users.find({place:{$in:[“NYC”,”SF”]})

Matches any of the values speciīŦed in an array. Find all users with the place īŦeld that is either NYC or SF.

$lt

db.users.deleteMany({“age”:{$lt:18})

Matches values that are less than a speciīŦed value. Deletes all users age less than 18.

$lte

db.users.updateMany({age:{$lte:17},{access:”invalid”})

Matches values that are less than or equal to a speciīŦed value. Updates all access to “invalid” for all users with an age less than or equal to 17.

$ne

db.users.find({“place”:{$ne:‘NYC”})

Matches all values that are not equal to a speciīŦed value. Find all users with the place īŦeld set to anything other than NYC.

$nin

db.users.find({ place:{$nin:[“NYC”,”SF”]})

Matches none of the values speciīŦed in an array. Find all users with a place īŦeld that does not equal NYC or SF.
Field Update Operators

Use the following inside an update object to make complex updates

Keyword Description

$inc

db.users.updateOne({age:22},{$inc:{age:3}})

Increments the value of the īŦeld by the speciīŦed amount. Adds 3 to the age of the īŦrst user with the age of 22.

$min 

db.scores.insertOne({_id:1,highScore:800,lowScore:200})    

db.scores.updateOne({_id:1},{$min:{lowScore:150}})

Only updates the īŦeld if the speciīŦed value is less than the existing īŦeld value. Creates a scoles collection and sets the value of highScore to 800 and lowScore to 200.   $min compares 200 (the current value of lowScore) to the speciīŦed value of 150. Because 150 is less than 200, $min will update lowScore to 150. Only updates the īŦeld if the speciīŦed value is greater than the existing īŦeld value. 

$max 

db.scores.updateOne( { _id: 1 }, { $max: { highScore: 1000}})

Only updates the īŦeld if the speciīŦed value is less than the existing īŦeld value. Creates a scoles collection and sets the value of highScore to 800 and lowScore to 200. $max compares 800 (the current value of highScore) to the speciīŦed value of 1000. Because 1000 is more than 800, $max will update highScore to 1000.

$rename

db.scores.updateOne( { $rename: { ‘highScore’: ‘high’} )

Renames a īŦeld. Renames the īŦeld ‘highScores’ to ‘high’,

$set

db.users.updateOne({ $set: { name: “valid user” } })

Sets the value of a īŦeld in a document. Replaces the value of the name īŦeld with the speciīŦed value valid user.

$unset

db.users.updateOne({ $unset: { name: “” } })

Removes the speciīŦed īŦeld from a document. Deletes the speciīŦed value valid user from the name īŦeld.

Read ModiīŦers

Add any of the following to the end of any read operation

Keyword Description

cursor.sort()

db.users.find().sort({ name: 1, age: -1 })

Orders the elements of an array during a $push operation. Sorts all users by name in alphabetical order and then if any names are the same sort by age in reverse order
cursor.limit() SpeciīŦes the maximum number of documents the cursor will return.
cursor.skip() Controls where MongoDB begins returning results.

cursor.push()

db.users.updateMany({}, { $push: { friends: “Chris” } })

Appends a speciīŦed value to an array. Add Chris to the friends array for all users
Aggregation Operations

The Aggregation Framework provides a speciīŦc language that can be used to execute a set of aggregation operations (processing & computation) against data held in MongoDB.

Keyword Description

db.collection.aggregate()

db.users.aggregate([ {$match: { access: “valid” } }, {$group: { _id: “$cust_id”, total:{$sum: “$amount” } } }, {$sort: { total: -1 } }])

A method that provides access to the aggregation pipeline.   Selects documents in the users collection with accdb.orders.estimatedDocumentCount({})_id īŦeld from the sum of the amount īŦeld, and sorts the results by the total īŦeld in descending order:
Aggregation Operations

Aggregation pipelines consist of one or more stages that process documents and can return results for groups of documents.

Keyword Description
count Counts the number of documents in a collection or a view.
distinct Displays the distinct values found for a speciīŦed key in a collection or a view.
mapReduce Run map-reduce aggregation operations over a collection
Aggregation Operations

Single Purpose Aggregation Methods aggregate documents from a single collection. db.collection.count()   db.users.count({})Returns a count of the number of documents in a collection or a view. Returns the distinct values for the age īŦeld from all documents in the users collection.

Keyword Description
db.collection.estimatedDocument Returns an approximate count of the
Count() documents in a collection or a view.
db.users.estimatedDocumentCount({}) Retrieves an approximate count of all the documents in the users collection.
db.collection.distinct()     db.users.distinct(“age”) Returns an array of documents that have distinct values for the speciīŦed īŦeld. Returns the distinct values for the age īŦeld from all documents in the users collection.
Indexing Commands

Indexes support the eicient execution of queries in MongoDB. Indexes are special data structures that store a small portion of the data set in an easy-to-traverse form.

Replication Commands

Replication refers to the process of ensuring that the same data is available on more than one MongoDB Server.

Keyword Description
rs.add() Adds a member to a replica set. rs.add( “mongodbd4.example.net:27017” Adds a new secondary member, ) mongodbd4.example.net:27017, with default vote and priority settings to a new replica set
rs.conf() Returns a document that contains the current replica set conīŦguration.
rs.status() Returns the replica set status from the point of view of the member where the method is run.
rs.stepDown() Instructs the primary of the replica set to become a secondary. After the primary steps down, eligible secondaries will hold an election for primary.
rs.remove() Removes the member described by the hostname parameter from the current replica set.
rs.reconfig() ReconīŦgures an existing replica set, overwriting the existing replica set conīŦguration.
Sharding Commands

Sharding is a method for distributing or partitioning data across multiple computers. This is done by partitioning the data by key ranges and distributing the data among two or more database instances.

Keyword Description
sh.abortReshardCollection() Ends a resharding operation sh.abortReshardCollection(“users”) Aborts a running reshard operation on the users collection.
sh.addShard() dds a shard to a sharded cluster. sh.addShard(“cluster”/mongodb3.exampl Adds the cluster replica set and speciīŦes one e.net:27327”) member of the replica set.
sh.commitReshardCollection Forces a resharding operation to block () writes and complete. sh.commitReshardCollection(“records.u Forces the resharding operation on the sers”) records.users to block writes and complete.
sh.disableBalancing() Disable balancing on a single collection in a sharded database. Does not afect balancing of other collections in a sharded cluster. sh.disableBalancing(“records.users”)    Disables the balancer for the speciīŦed sharded collection.
sh.enableAutoSplit() Enables auto-splitting for the sharded cluster.
sh.disableAutoSplit() Disables auto-splitting for the sharded cluster.
sh.enableSharding() Creates a database. sh.enablingSharding(“records”)          Creates the records database.
sh.help() Returns help text for the sh methods.
sh.moveChunk() Migrates a chunk in a sharded cluster. sh.moveChunk(“records.users”, {  Finds the chunk that contains the documents zipcode: “10003” }, “shardexample”)  with the zipcode īŦeld set to 10003 and then moves that chunk to the shard named shardexample.
sh.reshardCollection() Initiates a resharding operation to change the shard key for a collection, changing the distribution of your data. sh.reshardCollection(“records.users”, Reshards the users collection with the new { order_id: 1 })                       shard key { order_id: 1 }
sh.shardCollection() Enables sharding for a collection. sh.shardCollection(“records.users”,     Shards the users collection by the zipcode { zipcode: 1 } ) īŦeld.
sh.splitAt() Divides an existing chunk into two chunks using a speciīŦc value of the shard key as the dividing point. sh.splitAt( “records.users”, { x: 70    Splits a chunk of the records.users collection at } ) the shard key value x: 70
sh.splitFind() Divides an existing chunk that contains a document matching a query into two approximately equal chunks. sh.splitFind( “records.users”, { x:70 Splits, at the median point, a chunk that } ) contains the shard key value x: 70.
sh.status() Reports on the status of a sharded cluster, as db.printShardingStatus().
sh.waitForPingChange() Internal. Waits for a change in ping state from one of the mongos in the sharded cluster.
refineCollectionShardKey ModiīŦes the collection’s shard key by adding new īŦeld(s) as a suix to the existing key. db.adminCommand( { shardCollection:     Shard the orders collection in the test “test.orders”, key: { customer_id: 1    database. The operation uses the customer_id } } ) īŦeld as the initial shard key.   db.getSiblingDB(“test”).orders.create Create the index to support the new shard key Index( { customer_id: 1, order_id: 1    if the index does not already exist. } )   db.adminCommand( {Run reīŦneCollectionShardKey command to refineCollectionShardKey: add the order_id īŦeld as a suix “test.orders”, key: { customer_id: 1, order_id: 1 } } )
convertShardKeyToHashed()  Returns the hashed value for the input. use test Consider a sharded collection that uses a db.orders.createIndex( { _id:hashed shard key. “hashed” } ) sh.shardCollection( “test.orders”, { _id : “hashed” } ) { If the following document exists in the _id:collection, the hashed value of the _id īŦeld is ObjectId(“5b2be413c06d924ab26ff9ca”), used to distribute the document: “item” : “Chocolates”, “qty” : 25 } convertShardKeyToHashed(Determine the hashed value of _id īŦeld used ObjectId(“5b2be413c06d924ab26ff9ca”) to distribute the document across the shards, )
Database Methods
Keyword Description
db.runCommand() Run a command against the current database
db.adminCommand() Provides a helper to run speciīŦed database commands against the admin database.
User Management Commands

Make updates to users in the MongoDB Shell.

Keyword Description
db.auth() Authenticates a user to a database.
db.changeUserPassword() Updates a user’s password.
db.createUser() Creates a new user for the database on which the method is run.
db.dropUser() Removes user/all users from the db.dropAllUsers() current database.
db.getUser() Returns information for a speciīŦed db.getUsers() user/all users in the database.
db.grantRolesToUser() Grants a role and its privileges to a user.
db.removeUser() Removes the speciīŦed username from the database.
db.revokeRolesFromUser() Removes one or more roles from a user on the current database.
db.updateUser() Updates the user’s proīŦle on the database on which you run the method.
passwordPrompt() Prompts for the password in mongosh.
Role Management Commands

Make updates to roles in the MongoDB Shell.

Keyword Description
db.createRole() Authenticates a user to a database.
db.dropRole() Deletes a user-deīŦned role/all db.dropAllRoles() user-deīŦned roles associated with a database.
db.getRole() Returns information for the speciīŦed db.getRoles() role/all the user-deīŦned roles in a database.
db.grantPrivilegesToRole() Assigns privileges to a user-deīŦned role.
db.revokePrivilegesFromRole() Removes the speciīŦed privileges from a user-deīŦned role.
db.grantRolesToRole()     SpeciīŦes roles from which a user-deīŦned role inherits privileges.
db.revokeRolesFromRole() Removes inherited roles from a role.
db.updateRole() Updates a user-deīŦned role.
MongoDB Cheat Sheet

Leave a Comment