Mongodb Cheat Sheet
Overview
The NoSQL database tool MongoDB is adaptable, document-focused, and can expand to any business volume without sacrificing search speed. It is a distributed, unbacked store with a JSON-like data schema that utilises several servers. Developers of web and business applications who need flexibility and effective scaling prefer utilising MongoDB. Developers of all stripes who use agile development methodologies to build scalable systems will find MongoDB to be very useful. Do you require a fast reference guide for a typical MongoDB Cheat Sheet? We'll go through a complete list of every MongoDB Cheat Sheet command you might require in this article. Nearly all of the most popular MongoDB commands are included in this MongoDB Cheat Sheet.
What is MongoDB?
MongoDB is a NoSQL database, which means it cannot be queried using SQL. Other than that, NoSQL signifies nothing when it comes to defining a database. So let's try defining MongoDB once more. A JSON document data storage is MongoDB. With a few smarts on top, it enables you to store and search for documents in JSON format. This implies that objects with nested data may all be stored in a single collection (collections in MongoDB are analogous to tables in RDBMS.
Pros of MongoDB:
- Schema-less Model: Applications are given the authority and obligation to interpret various attributes present in the documents of a collection.
- Flexibility: MongoDB is expressive and adaptable because it employs documents that can have sub-documents in deep hierarchies. Any computer language's objects may be mapped by MongoDB, making implementation and upkeep simple.
- Modular Query Model: With as many properties per object as required by the application layer, the user may choose to index particular portions of each document or a query based on ranges, attribute values, or regular expressions.
- Aggregation of Natives: Users can extract and manipulate data from the database using native aggregation. The data may either be exported to other data sources or put into a new format.
Features
- Replication: High availability is made possible via the MongoDB replica set functionality. A replica set of data consists of two or more copies. As a primary or secondary replica, a replica set serves as such. The replica set automatically chooses which secondary should take over as the primary whenever a primary replica collapses and, if required, holds an election. Although read operations may also be supported by secondary copies, the data is only initially consistent.
- Sharding: Data splitting among machines is known as sharding. By distributing data across them, we can store more data and manage more load without modernising our equipment. By dividing a collection over several computers (shards), MongoDB's sharding feature enables collections to grow beyond the bounds of available resources.
- Aggregation: MongoDB offers the map-reduce function, the aggregation pipeline and specific-purpose aggregation techniques. The documentation for MongoDB claims that the Aggregation Pipeline outperforms map-reduce for the majority of aggregation operations. Users may achieve the same kinds of results that the SQL GROUP BY clause produces by using the aggregation framework.
- Indexing: Primary and secondary indexes can be used to index a MongoDB field. A tiny subset of the data set is kept in an easy-to-navigate format in a MongoDB index. An index keeps track of a field's or group of fields' values in descending order of value. By keeping a tiny piece of the data set in a useful format, indexes in MongoDB help to effectively resolve queries. An index in MongoDB is comparable to an index in a normal relational database.
Connecting MongoDB Shell
The first thing to include in MongoDB Cheat Sheet is to connect to the Mongo shell.
Follow the commands given below to connect to the mongoDB shell:
Use your server prompt to enter the Mongo command to launch the MongoDB shell. The Mongo command by default launches a shell connected to a MongoDB instance that is installed locally and running on port 27017.
Try executing the Mongo command without any extra arguments:
This will output a welcome message that includes details about the server the shell is connecting to and the installed version of MongoDB. The MongoDB shell prompt, denoted by a greater-than symbol, will display below that.
You can also enter a username and password to authenticate into a MongoDB instance.
The —host is used to specify the host address, —port to specify the port at which the instance is running,-u for the username and -p for the password.
You can also use MongoUri to connect to a MongoDB instance.
Database Commands
Database: A container for collections. This is the same as a database in SQL and usually, each project will have its database full of different collections.
MongoDB Cheat Sheet Database Commands :
-
Use the following command to view all databases:
show dbs -
Command to switch to a particular database:
use databasename -
To view the current database you can use:
show db -
Execute the following command to delete the database, which will delete the current database:
databasename.dropDatabase()
Collection Commands
Collection: A grouping of documents inside of a database. This is the same as a table in SQL and usually each type of data (users, posts, products) will have its own collection.
MongoDB Cheat Sheet collection Commands:
-
In the current database to view all the collections use the below command:
show collections -
Execute the following instructions to create the new collection:
db.createCollection('collectionname') -
Execute the following command to remove the chosen collection:
Syntax: db.col.drop() -
Command to list the collection’s records:
db.collectionname.find()
Document (row) Commands
MongoDB Cheat Sheet Document Commands:
Document: A record inside of a collection. This is the same as a row in SQL and usually, there will be one document per object in the collection. A document is also essentially just a JSON object.
Collections are created using the MongoDB function db.createCollection(name, options). name refers to the name of the newly created collection in the command. options is a document that describes how to configure a collection, including things like memory size and indexing.
-
Execute the following command to get the list of documents in the collection:
db.COLLECTION_NAME.find() -
To show all the rows in a collection in a prettified way add .pretty() after .find():
db.COLLECTION_NAME.find().pretty() -
The find command can also be used to fetch the documents with the specified criteria:
db.COLLECTION_NAME.find({propertyName : "propertyValue"}) -
Command to limit the number of rows in the output:
db.col.find().limit(10) -
Command to count the number of rows in the output:
db.col.find().count()
MongoDB Cheat Sheet Operators:
Operator | Description | Command |
---|---|---|
$gt | greater than | db.docx.find({class:{$gt:'T'} |
$gte | greater than equals | db.docx.find({class:{$gt:'T'} |
$lt | less than | db.docx.find({class:{$lt:'T'} |
$lte | less than equals | db.docx.find({class:{$lte:'T'} |
$exists | does an attribute exist or not | db.docx.find({class:{$gt:'T'} |
$regex | Matching pattern in pearl-style | db.docx.find({name:{$regex:'^USS\\sE'}}) |
$type | Search by type of an element | db.docx.find({name : {$type:4}}) |
Helper Commands
The following commands are used to get information about the databases and collections, and for other utility purposes also. They often come in handy.
MongoDB Cheat Sheet Helper Commands:
- Command to show all the database: show dbs
- Command to switch to a particular database: use databasename
- Command to view all collections in the current database: show collections
- Command to run a javascript file: load("filename.js")
CRUD
The techniques that MongoDB exposes for storage management are called CRUD Operations. Create, Read, Update, and Delete is referred to as CRUD. These four fundamental techniques let you browse, search, and modify the resources in your database.
Each of these commands is run on a specific collection:
db.<collectionName>.<command>
MongoDB Cheat Sheet Create Commands:
-
Command to create a new document inside a specified collection:
db.collectionname.insertOne({ user: “xyz” }) -
Command to create multiple new documents inside a specified collection:
db.collectionname.insertOne([{ user: "xyz" }, {user: "abc"}])
MongoDB Cheat Sheet Read Commands:
-
Command to show all the documents (it returns a cursor):
db.collectionname.find() -
Command to show only one document : db.collectionname.findOne()
-
Command to show all the documents in a prettified way:
db.collectionname.find().pretty() -
Command to find all documents that match the filter object but only (Get all users with the name abc but only return their age, and _id):
db.collectionname.find({ user: “abc” }, { age: 1 }) -
Command to return the count of the documents that match the filter:
db.collectionname.countDocuments({ user: "abc" })
MongoDB Cheat Sheet Update Commands:
-
Command to update the first document that matches the filter object with the data passed into the second parameter which is the update object:
db.collectionname.updateOne({ name: "abc" }, { $set: { name: "xyz" } }) -
Command to update all documents that match the filter object with the data passed into the second parameter which is the update object:
db.collectionname.updateMany({ age: 20 }, { $inc: { age: 1 } }) -
Command to replace the first document that matches the filter object with the exact object passed as the second parameter. This will completely overwrite the entire object and not just update individual fields:
db.collectionname.replaceOne({ name: "abc" }, { name: "xyz" })
MongoDB Cheat Sheet Delete Commands:
- Command to delete the first document that matches the filter object:
db.collectionname.deleteOne({ name: "abc" }) - Command to delete all documents that match the filter object:
db.collectionname.deleteMany({ name: "abc" }) - Command to delete all the documents in a collection but not the collection itself:
db.collectionname.remove({})
Indexes
Indexes are specialised data structures that keep a discrete subset of the data set in an accessible format. The value of a particular field or collection of fields is stored in the index, ordered by the value of the field as indicated in the index.
MongoDB Cheat Sheet Indexes Commands :
-
Command to List all the indexes of a collection:
db.collectioname.getIndexes() -
The createIndex method in MongoDB is used to create an index:
db.collectioname.createIndex({"name": 2}) -
Command to create a compound index:
db.collectioname.createIndex({"name": 1, "date": 1}) -
dropIndex Command is used to drop the index. The Fields that need to be removed from the Index are taken by the dropIndex method:
db.collectionanme.dropIndex("name_2") -
Command to hide indexes:
db.collectionanme.hideIndex("name_1") -
Command to unhide indexes: db.collectionanme.hideIndex("name_1")
Handy Commands in MongoDB
MongoDB Cheat Sheet Handy Commands:
Use Admin
- Command to create a user: db.createUser({"user": "root", "pwd": passwordPrompt(), "roles": ["xyz"]})
- Command to drop a user: db.dropUser("root")
- Command to authenticate mongoDB database: db.auth( "user", passwordPrompt() )
Use Test
- Command to return another database without modifying the db variable in the shell environment: db.getSiblingDB("dbname")
- Command to return a document that contains information on in-progress operations for the database: instancedb.currentOp()
- Command to kill queries: db.killOp(345) // opi
- Command to sort the results of a find by the given fields: db.collectionname.find().sort({ name: 1, age: -1 })
- Command to skip a set number of documents from the beginning: db.collectionname.find().skip(2)
MongoDB Change Streams
Applications can subscribe to all data changes on a single collection, a database, or an entire deployment using change streams, and they can then respond right away to them. Applications can filter for particular changes or alter the notifications at will because change streams employ the aggregation framework.
MongoDB Cheat Sheet Stream Commands:
In the above example, a change stream cursor has been made on the coll collection and insert operation. If the cursor is closed and there are no more items in the batch, the function cursor.isExhausted() returns true.
Sharded Cluster
Sharding, MongoDB's method for addressing the demands of data growth, is the process of storing data records across many machines.
MongoDB Cheat Sheet Sharded Cluster Commands:
-
Command to print information regarding existing chunks in a sharded cluster and sharding configuration:
sh.status() The above command outputs a structured report of a sharded cluster's sharding configuration and information about the chunks that are currently in use. -
Command to add a shard replica set to a sharded cluster:
sh.addShard("rs1/mongodbd1.example.net:27017") Creates a shard replica set and adds it to the cluster. -
To prevent chunks from getting too big, MongoDB automatically splits them based on the shard key values that each chunk represents when auto-splitting is enabled for a sharded cluster.
Command to disable the auto split flag:
sh.disableAutoSplit() Command to enable the auto split flag:
sh.enableAutoSplit() -
A background process called the MongoDB balancer keeps track of how much data is present on each shard for each sharded collection.
Command to start balancer in a sharded cluster:
sh.startBalancer() -
Command to disable auto-splitting for the sharded cluster: sh.stopBalancer()
-
Command to return the document with the status of the balancer: sh.isBalancerRunning()
Replica Set
A collection of mongod instances that look after the same data set is known as a replica set. Multiple data-bearing nodes and, if present, one arbitrator node make up a replica set. One and only one member of the data-bearing nodes is considered the primary node, and the others are considered secondary nodes.
MongoDB Cheat Sheet Replica Set Commands:
- Command to return the replica set status from the member's point of view: rs.status()
- Command to add a member to replica set: rs.add()
- Command to remove a member from replica set: rs.remove("mongo.ex.net:27017"
- Command to return the current configuration setting of replica set: rs.conf()
- Command to make the primary replica set secondary: rs.stepDown()
- Command to get basic help text: rs.help
FAQs
Q. What does sharding in MongoDB means?
A. The process of dividing a sizable database into numerous databases and storing them on various machines is known as database sharding. Sharding is a procedure that can improve performance, speed up query responses, and allow the team to grow without affecting the application's availability.
Q. What is aggregation in MongoDB?
A. Aggregation in Mongodb is the process of going through various phases with a huge collection of documents to process them. A pipeline is made up of several stages. Filtering, sorting, grouping, reshaping, and altering documents as they move through a pipeline are all possible.
Q. What is the use of Replica set in MongoDB?
A. The replica set helps with the following:
- To safeguard your data
- High-availability data (24/7) Disaster recovery
- There are no downtimes for backups, index rebuilds, or compaction.
- (Additional copies to read from) Read scaling
- The application is transparent to the replica set.
Conclusion
- MongoDB is a JSON document data storage.
- MongoDB offers a fully cloud-based platform for managing and distributing data to applications and is built on a distributed scale-out architecture.
- MongoDB offers flexibility, a Schema-less model, Modular Query Model and aggregation.
- Popular features of mongoDB are replication, indexing, sharding and aggregation.
- The process of dividing a sizable database into numerous databases and storing them on various machines is known as database sharding.
- Indexes are specialised data structures that keep a discrete subset of the data set in an accessible format.
- To compare and refer to document attributes, you can use a variety of query Mongo DB Operators.
- A collection of mongod instances that look after the same data set is known as a replica set.