Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Mongo DB FULL CHEATSHEET , MUST FOR REVISION, Cheat Sheet of Web Design and Development

You can easily learn Mongo DB (backend development) uing this cheetsheet or notes.

Typology: Cheat Sheet

2024/2025

Available from 07/04/2025

ritesh-kumar-41
ritesh-kumar-41 🇺🇸

3 documents

1 / 15

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
MongoDB Shell Cheat Sheet
To get started, install the MongoDB Shell (mongosh).
Basic Commands
These basic help commands are available in the MongoDB Shell.
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 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-defined and built-in, for the
current database.
show profile
Print the five most recent operations
that took 1 millisecond or more on
databases with profiling enabled.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Mongo DB FULL CHEATSHEET , MUST FOR REVISION and more Cheat Sheet Web Design and Development in PDF only on Docsity!

MongoDB Shell Cheat Sheet

To get started, install the MongoDB Shell (mongosh).

Basic Commands

These basic help commands are available in the MongoDB Shell. 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..help() db.users.help() Show help on collection methods. The 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 Switch current database to . 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-defined and built-in, for the current database. show profile Print the five most recent operations that took 1 millisecond or more on databases with profiling 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 add new documents to a collection. If the collection does not exist, create operations also create the collection. 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 age of 24 and 38 into the users collection

Read Operations

Read operations retrieve documents from a collection; i.e. query a collection for documents. db.collection.find() db.users.find() Selects documents in a collection or view and returns a cursor to the selected documents. Returns all users. db.collection.find() db.users.find({place: "NYC"}) Find all documents that match the filter object Returns all users with the place NYC. db.collection.find({:1,< field>:1}) db.users.find({status:1,item:1}) Returns all documents that match the query after you explicitly include several fields by setting the to 1 in the projection document. Returns matching documents only from state field, item field and, by default, the _id field.

Comparison Query Operators

Use the following inside an filter object to make complex queries $eq db.users.find({ system: { $eq: "macOS" } }) Matches values that are equal to a specified value. Finds all users with the operating system macOS. $gt db.users.deleteMany({ age: { $gt: 99} }) Matches values that are greater than a specified value. Deletes all users with an age greater than 99. $gte db.users.updateMany({ age": {$gte: },{access: "valid"}) Matches values that are greater than or equal to a specified 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 specified in an array. Find all users with the place field that is either NYC or SF. $lt db.users.deleteMany({ "age": {$lt: }) Matches values that are less than a specified value. Deletes all users with the age less than 18.. $lte db.users.updateMany({ age: { $lte: 17 }, {access: "invalid"}) Matches values that are less than or equal to a specified 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 specified value. Find all users with the place field set to anything other than NYC.

$nin db.users.find( { place: { $nin: [ "NYC", "SF" ] } ) Matches none of the values specified in an array. Find all users with the place field that does not equal NYC or SF.

Field Update Operators

Use the following inside an update object to make complex updates $inc db.users.updateOne({ age: 22 }, { $inc: { age: 3} }) Increments the value of the field by the specified amount. Adds 3 to the age of the first 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 field if the specified value is less than the existing field 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 specified value of 150. Because 150 is less than 200, $min will update lowScore to 150. $max db.scores.updateOne( { _id: 1 }, { $max: { highScore: 1000 } } ) Only updates the field if the specified value is greater than the existing field value. $max compares 800 (the current value of highScore) to the specified value of 1000. Because 1000 is more than 800, $max will update highScore to 1000. $rename db.scores.updateOne( { $rename: { 'highScore': 'high'} ) Renames a field. Renames the field ‘highScores’ to ‘high’,

Aggregation Operations

The Aggregation Framework provides a specific language that can be used to execute a set of aggregation operations (processing & computation) against data held in MongoDB. 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 field from the sum of the amount field, and sorts the results by the total field in descending order:

Aggregation Operations

Aggregation pipelines consist of one or more stages that process documents and can return results for groups of documents. count Counts the number of documents in a collection or a view. distinct Displays the distinct values found for a specified 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.estimatedDocument Count() db.users.estimatedDocumentCount({}) Returns an approximate count of the documents in a collection or a view. Retrieves an approximate count of all the documents in the users 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 field from all documents in the users collection. db.collection.distinct() db.users.distinct("age") Returns an array of documents that have distinct values for the specified field. Returns the distinct values for the age field from all documents in the users collection.

Indexing Commands

Indexes support the ecient 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. db.collection.createIndex() db.users.createIndex("account creation date") Builds an index on a collection. Creates the account creation date index in the users collection. db.collection.dropIndex() db.users.dropIndex("account creation date") Removes a specified index on a collection. Removes the account creation date index from the users collection. db.collection.dropIndexes() db.users.dropIndexes() db.users.dropIndex("account creation date", "account termination date") Removes all indexes but the _id (no parameters) or a specified set of indexes on a collection. Drop all but the _id index from a collection. Removes the account creation date index and the account termination date index from the users collection.

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() Reconfigures an existing replica set, overwriting the existing replica set configuration.

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. sh.abortReshardCollection() sh.abortReshardCollection("users") Ends a resharding operation Aborts a running reshard operation on the users collection. sh.addShard() sh.addShard("cluster"/mongodb3.exampl e.net:27327") Adds a shard to a sharded cluster. Adds the cluster replica set and specifies one member of the replica set. sh.commitReshardCollection () sh.commitReshardCollection("records.u sers") Forces a resharding operation to block writes and complete. Forces the resharding operation on the records.users to block writes and complete.

sh.disableBalancing() sh.disableBalancing("records.users") Disable balancing on a single collection in a sharded database. Does not aect balancing of other collections in a sharded cluster. Disables the balancer for the specified sharded collection. sh.enableAutoSplit() Enables auto-splitting for the sharded cluster. sh.disableAutoSplit() Disables auto-splitting for the sharded cluster. sh.enableSharding() sh.enablingSharding("records") Creates a database. Creates the records database. sh.help() Returns help text for the sh methods. sh.moveChunk() sh.moveChunk("records.users", { zipcode: "10003" }, "shardexample") Migrates a chunk in a sharded cluster. Finds the chunk that contains the documents with the zipcode field set to 10003 and then moves that chunk to the shard named shardexample. sh.reshardCollection() sh.reshardCollection("records.users", { order_id: 1 }) Initiates a resharding operation to change the shard key for a collection, changing the distribution of your data. Reshards the users collection with the new shard key { order_id: 1 } sh.shardCollection() sh.shardCollection("records.users", { zipcode: 1 } ) Enables sharding for a collection. Shards the users collection by the zipcode field.

convertShardKeyToHashed() use test db.orders.createIndex( { _id: "hashed" } ) sh.shardCollection( "test.orders", { _id : "hashed" } ) { _id: ObjectId("5b2be413c06d924ab26ff9ca"), "item" : "Chocolates", "qty" : 25 } convertShardKeyToHashed( ObjectId("5b2be413c06d924ab26ff9ca") ) Returns the hashed value for the input. Consider a sharded collection that uses a hashed shard key. If the following document exists in the collection, the hashed value of the _id field is used to distribute the document: Determine the hashed value of _id field used to distribute the document across the shards,

Database Methods

db.runCommand() Run a command against the current database db.adminCommand() Provides a helper to run specified database commands against the admin database.

User Management Commands

Make updates to users in the MongoDB Shell. 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() db.dropAllUsers() Removes user/all users from the current database. db.getUser() db.getUsers() Returns information for a specified user/all users in the database. db.grantRolesToUser() Grants a role and its privileges to a user. db.removeUser() Removes the specified username from the database. db.revokeRolesFromUser() (^) Removes one or more roles from a user on the current database. db.updateUser() Updates the user's profile on the database on which you run the method. passwordPrompt() Prompts for the password in mongosh.