
MongoDB, the most popular open-source document-oriented database is a NoSQL type of database. NoSQL database stands for Non-Structured Query Database. MongoDB stores the data in the form of the structure(field:value pair) rather than tabular form. … A simple example of a MongoDB database collection.
- Introduction to MongoDB
- Characteristics of MongoDB
- Illustrations of Cases Where MongoDB’s Adaptability Is Beneficial
- MongoDB Architecture’s Core Elements
- How Are Privacy and Data Security Protected by MongoDB?
- What is MongoDB Query?
- Querying MongoDB Collection
- Managing Indexes
- MongoDB pros and cons
- Conclusion
Introduction to MongoDB
The class of document-oriented databases includes the well-known open-source NoSQL database management system MongoDB. It saves data in adaptable, JSON-like documents known as BSONs (Binary JSON), which are designed to manage unstructured or semi-structured data. MongoDB is well-suited for a variety of contemporary online applications, mobile apps, IoT projects, and big data use cases because to its scalability, performance, and ease of use.

- Flexibility of the Schema: MongoDB’s dynamic schema enables easy management of changing data structures without rigid schema definitions, allowing documents to include various fields in collections.
- Durability and effectiveness: The horizontal scalability of MongoDB allows you to manage enormous amounts of data and high write and read speeds by distributing data across several servers or nodes.
- Query Rich Language: You may run complicated queries, filtering, sorting, and aggregations on your data using MongoDB’s robust query language.
- Superior Availability and Tolerance to Faults: Replica sets, one feature offered by MongoDB, maintain multiple copies of data across servers automatically, ensuring data availability and fault tolerance.
Characteristics of MongoDB

- CMS solutions handle unstructured data with MongoDB, enabling content storage and management without preset models.
- MongoDB’s flexible structure enables efficient processing and analysis of diverse log data for real-time analysis.
- Sensors in IoT devices produce large amounts of semi-structured data, making MongoDB an ideal storage solution for managing sensor, telemetry, and logs without requiring a predefined schema.
Illustrations of cases where MongoDB’s adaptability is beneficial
- MongoDB Server: MongoDB server manages data storage, retrieval, and processing, operating independently or as a replica set or sharded cluster for increased availability and scalability.
- Documents for the data model: MongoDB’s document-oriented data paradigm is based on BSON documents, which represent single database records with flexible schema architectures.
- Replica Sets: MongoDB uses replica sets for high availability and data redundancy, with multiple instances acting as primary and secondary nodes. This ensures data durability and fault tolerance.
- Sharded Cluster: MongoDB uses sharded clusters for horizontal scaling, dividing data into distinct replica sets based on a shard key, enabling efficient handling of large datasets.
- Migration of Chunks and Balancing: MongoDB handles data balancing and distribution through chunk migration, ensuring equitable distribution and optimal performance in shards.
- Wire Protocol: The communication between client software and the MongoDB server is outlined in the MongoDB wire protocol. It outlines the structure and network transmission of requests and answers.
MongoDB Architecture’s Core Elements
A flexible and scalable NoSQL database solution can be obtained by the MongoDB architecture, which is composed of an assortment of significant components. The core elements of the architecture of MongoDB are listed below:
- To limit access to the database, MongoDB supports authentication. preventing anyone but permitted users from accessing the data, administrators can create user accounts with specified responsibilities and permissions.
- MongoDB uses Role-Based Access Control to control user permissions based on individual duties, allowing read-only, read-write, or administrative roles.
- MongoDB’s IP whitelisting feature allows administrators to create a list of trusted IP addresses or CIDR blocks, restricting access to authorized networks.
- Options for encrypting data both at rest and in transit are available with MongoDB. Using functions like Transparent Data Encryption (TDE) or outside encryption programmes, data at rest can be encrypted. To secure data, SSL/TLS encryption is employed in transit while it is transmitted over networks.
- Field-level redaction is a feature of MongoDB that enables sensitive data to be concealed or masked from specific users or roles. This guards against unauthorised access to private data.
How are privacy and data security protected by MongoDB?
To guarantee data security and privacy, MongoDB offers a number of features and techniques. Here are a few essential components of MongoDB’s strategy for data security:

- Finding a Single Document
- In MongoDB, we can find a single document using the findOne() method. This method returns the first document that matches the given filter query expression.
- syntax :
- db.Collection_name.findOne()
- Example :
- db.article.findOne()
- Here, we are going to display the first document of article collection
- Display documents in formatted way
- In MongoDB, we can use the beautiful() method to display the documents of a specified collection in a nicely formatted way.
- syntax :
- db.Collection_name.find(). Beautiful ()
- Example :
- db.article.find(). Beautiful ()
- Here, we are going to display the articles archive documents in a nicely formatted way by using the beautiful() method
- similar filter query
- The equality operator ($eq) is used to match documents where the value of the field is equal to the specified value. In other words, the $eq operator is used to specify the equality condition.
- syntax :
- db.collection_name.find({<'key > : {$eq : <'value>}})
- Example :
- db.article.find({author:{$eq:”devil”}}). Beautiful ()
- Here, we’re going to display the documents that match the filter query (ie, {author: {$eq: “devil”}}) from the articles collection.
- larger than filter query
- Use the $gte or $lte operator in the find() method to get specific numeric data using conditions such as greater than equal or less than equal.
- syntax
- db.collection_name.find({<'key > : {$gte : <'value>}})
- or
- db.collection_name.find({<'key > : {$lte : <'value>}})
- Example
- db.article.find({length: {$gte:510}}). Beautiful ()
- Here, we are querying to get the documented data in which the length attribute value is greater than 510. Therefore, we pass a filter query that is {length: {$gte: 510}} to the find() method.
- check existence filter query
- The $exists operator shows all archive documents if they exist on a given key.
- syntax
- db.collection_name.find({<'key> : {$exists: <'boolean>}})
- Example
- db.article.find({time: {$exists: “true”}}). Beautiful ()
- Here, we’re going to look at all documents that contain time by passing a filter query that is {time: {$exists : “true”}} to the find() method.
- Logical Operator Query
- The $AND operator belongs to the type of MongoDB logical operator that performs logical AND operations on an array of one or more expressions and selects or retrieves only those documents that match all the given expressions in the array.
- syntax
- db.collection_name.find({$and : [{<'key> : {$eq : <'value1 >}}, {<'key> : {$exists : <'boolean>}}]})
- Example
- db.article.find({$and:[{level:{$eq:”high”}},{level:{$exists : “true”}}]}).pretty()
- In this query example we are using the AND operator and given two conditions which are highlighted as follows:
- else operator: {$and : [first condition, second condition]}
- first condition (level == “high”): { level: { $eq: “high” } }
- Second condition: {level: {$exists: “true”}}
What is MongoDB Query?
MongoDB query is a way to get data from a MongoDB database. MongoDB queries provide simplicity in the process of getting data from a database, it is similar to SQL query in SQL database language. While performing a query operation, one can also use criteria or conditions which can be used to retrieve specific data from the database.
MongoDB provides a function name in the form of db.collection_name.find() to perform query operations on the database. In this post, we discussed this function in several ways using different methods and operators.
Database: geeksforgeeks
Archive: Articles
Note: The “pretty()” query function is solely used in this case to make the content in the database easier to read. (It is not required)
field selection
The find() method displays the database collection in a non-structured form ({<'key>:<'value>}), which contains the <'key> “id” auto generated by MongoDB and the data inserted by the user or administrator.
syntax:
db.collection_name.find()
Example:
db.article.find()
This method is used to display all the documents present in the article collection.

- > db.users.find(). limit (10)
- ,
- ,
- Search users by family name
- > db.users.find({“name.family”:”Smith”}). Calculation ()
- 1
- ,
- Note that we enclose “name.family” in quotes, because it has a dot in the middle.
- query document by numeric range
- // All posts with a “Like” field with more than one numeric value:
- > db.post.find ({likes: {$gt: 1}})
- // All posts with 0 likes
- > db.post.find({likes:0})
- // All posts that don’t have exactly 1 like
- > db.post.find ({likes: {$ne: 1}})
- Sort results by a field
- // Sort by age, in ascending order (smallest value first)
- > db.user.find(). sort({age: 1})
- ,
- “_id”: object id(“5ce45d7606444f199acfba1e”),
- “name”: {given: “Alex”, family: “Smith”},
- “email”: “email@example.com”,
- “age”: 27
- ,
- ,
- _id: object id(“5effaa5662679b5af2c58829”),
- Email: “email@example.com”,
- name: {given: “Jesse”, family: “Jio”},
- Age: 31
- ,
- ,
- // Sort by age, in descending order (largest value first)
- > db.user.find(). sort({age:-1})
- ,
- _id: object id(“5effaa5662679b5af2c58829”),
- Email: “email@example.com”,
- name: {given: “Jesse”, family: “Jio”},
- Age: 31
- ,
- ,
- “_id”: object id(“5ce45d7606444f199acfba1e”),
- “name”: {given: “Alex”, family: “Smith”},
- “email”: “email@example.com”,
- “age”: 27
- ,
- ,
Querying MongoDB Collection:
MongoDB Query Language (MQL) uses a syntax similar to documents, making it intuitive and easy to use for advanced queries. Let’s look at some MongoDB query examples.
Search a limited number of results

- create an index
- > db.user.createIndex({“name.family”: 1})
- create a unique index
- > db.user.createIndex({email: 1}, {unique: true})
- Unique indexes allow you to ensure that there is at most one record in the collection with a given value for that field – very useful with things like email addresses!
- View index on collection
- > db.user.getIndexes()
- ,
- ,
- “V” : 2,
- “key” : {
- “_id” : 1
- ,
- “name”: “_id_”,
- “ns”: “my_database.user”
- ,
- ,
- “V” : 2,
- “key” : {
- “name given” : 1
- ,
- “name” : “name.given_1”,
- “ns”: “my_database.user”
- ,
- ,
- Note that by default for easy document retrieval by primary key, the collection always has an index on the _id field, so any additional indexes after that will be listed.
- drop an index
- > db.user.dropIndex(“name.given_1”)
Managing Indexes:
MongoDB allows you to create indexes, even on nested fields in subdocuments, to make queries perform well, even when the collection is huge.

- Like other NoSQL databases, MongoDB does not require a predefined schema. It stores any type of data. It lets users create any number of fields in a document, making MongoDB databases easier to scale than relational databases.
- One of the benefits of using documents is that these objects map to native data types in many programming languages. In addition, having embedded documents reduces the need for database joins, which can reduce costs.
- One of the main features of MongoDB is its horizontal scalability, which makes it a useful database for companies running big data applications. In addition, sharding allows the database to distribute data across a set of machines. Newer versions of MongoDB also support the creation of fields of data based on a sharded key.
- MongoDB supports multiple storage engines and provides a pluggable storage engine API that allows third parties to develop their own storage engines for MongoDB.
- The DBMS also has built-in aggregation capabilities, which allow users to run MapReduce code directly on the database instead of running MapReduce on Hadoop. MongoDB also includes its own file system called GridFS, similar to Hadoop Distributed File System (HDFS). The file system is primarily used for storing files larger than BSON’s size limit of 16 MB per document. These similarities allow MongoDB to be used instead of Hadoop, although the database software integrates with Hadoop, Spark, and other data processing frameworks.
- Although MongoDB has some valuable advantages, it also has some disadvantages. With its automatic failover strategy, the user sets up only one master node in the MongoDB cluster. If the master fails, the second node will be automatically converted to the new master. This switch promises continuity, but it’s not instantaneous – it can take up to a minute. By comparison, Cassandra NoSQL databases support multiple master nodes so that if one master goes down, the other stands in for the highly available database infrastructure.
- MongoDB’s single master node also limits how fast data can be written to the database. Data writes must be recorded on the master, and writing new information to the database is limited by the capacity of that master node.
- Another potential problem is that MongoDB does not provide full referential integrity through the use of foreign-key constraints, which can affect data consistency. In addition, user authentication is not enabled by default in the MongoDB database, a nod to the technology’s popularity with developers. However, malicious hackers have targeted a large number of vulnerable MongoDB systems in ransom attacks, adding a default setting that blocks network connections to databases if they have not been configured by the database administrator.
MongoDB pros and cons:

Conclusion:
MongoDB is an open source NoSQL database management program. NoSQL is used as an alternative to traditional relational databases. NoSQL databases are quite useful for working with large sets of distributed data. MongoDB is a tool that can manage document-oriented information, store or retrieve information.
MongoDB supports different forms of data. It is one of several non-relational database technologies that originated under the NoSQL banner in the mid-2000s – in general, for use in big data applications and other processing tasks involving data that do well in a rigid relational model. Doesn’t fit well. Instead of using tables and rows as in a relational database, the MongoDB architecture is composed of collections and documents.
Organisations can use MongoDB for their ad-hoc queries, indexing, load balancing, aggregation, server-side JavaScript execution, and other features. The ultimate flexibility of MongoDB means that it is far from a comprehensive list of everything you can do with it! For more information, see the MongoDB documentation, or take a course at MongoDB University.