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.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.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.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(<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.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.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.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.users.deleteOne({age:37}) |
Removes a single document from a collection. Deletes the īŦrst user with the age of 37. |
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 |
db.users.find({ system:{$eq:âmacOSâ}}) |
Matches values that are equal to a speciīŦed value. Finds all users with the operating system macOS. |
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. |
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. |
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. |
db.users.deleteMany({âageâ:{$lt:18}) |
Matches values that are less than a speciīŦed value. Deletes all users age less than 18. |
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. |
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. |
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 |
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. |
db.scores.updateOne( { $rename: { âhighScoreâ: âhighâ} ) |
Renames a īŦeld. Renames the īŦeld âhighScoresâ to âhighâ, |
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. |
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. |
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.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 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. |
Leave a Comment