What is MongoDB and its Queries | All you need to know [ OverView ]
What is MongoDB and ts Queries ACTE

What is MongoDB and its Queries | All you need to know [ OverView ]

Last updated on 30th Dec 2021, Blog, General

About author

Neel Patel (MongoDB Manager )

Neel Patel is a MongoDB Manager for the Respective Industry and has 6+ years of experience working on JavaScript, HTML, CSS, Ajax, jQuery, MongoDB, ReactJS, and VueJS. His articles help to impart knowledge and skills in core fields and give insightful knowledge to students.

(5.0) | 19186 Ratings 926

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.

    • What is MongoDB?
    • MongoDB Features
    • MongoDB Example
    • Key Components of MongoDB Architecture
    • Why Use MongoDB?
    • What is MongoDB Query?
    • Querying MongoDB Collection
    • Managing Indexes
    • MongoDB pros and cons
    • Conclusion

    Subscribe For Free Demo

      What is MongoDB?

      MongoDB is a document-oriented NoSQL database used for high volume data storage. Instead of using tables and rows like traditional relational databases, MongoDB uses collections and documents. Documents consist of key-value pairs which are the basic unit of data in MongoDB. Collections contain sets of documents and functions that are equivalent to relational database tables. MongoDB is a database that came out in the mid-2000s.


      MongoDB Features:

    • Each database consists of collections which in turn contain documents. Each document may be different with different fields. The size and content of each document may differ from each other.

    • The document structure is consistent with how developers build their classes and objects in their respective programming languages. Developers will often say that their classes are not rows and columns, but a clear structure with key-value pairs.

    • Rows (or Documents called in MongoDB) do not need a schema already defined. Instead, farms can be created on the fly.

    • The data model available within MongoDB allows you to more easily represent hierarchical relationships, store arrays, and other more complex structures. Scalability – The MongoDB environment is very scalable. Companies around the world have defined clusters, some of which are running 100+ nodes with almost millions of documents in the database.

      MongoDB Example:

    • The example below shows how a document can be modelled in MongoDB.
    • The _id field is added by MongoDB to uniquely identify the document in the collection.
    • What you may note is that the order data (Order ID, Product and Quantity) that would normally be stored in a RDBMS would be stored in a separate table, whereas in MongoDB it would actually be stored as an embedded document in the collection. One of the key differences is how data is modelled in MongoDB.

      Key Components of MongoDB Architecture:

      Below are some common terms used in MongoDB _id – This is a required field in every MongoDB document. The _id field represents a unique value in a MongoDB document. The _id field is like the primary key of the document. If you create a new document without the _id field, MongoDB will automatically create the field. So for example, if we look at the example of the Customers table above, MongoDB will add a 24 digit unique identifier to each document in the collection.


      • _Id CustomerID CustomerName OrderID
      • 563479cc8a8a4246bd27d784 11 thur99 111
      • 563479cc7a8a4246bd47d784 22 Trevor Smith 222
      • 563479cc9a8a4246bd57d784 33 nicole 333

      Collection – This is a set of MongoDB documents. A collection is equivalent to a table that is created in another RDBMS such as Oracle or MS SQL. A collection exists within a database. As can be seen from the introduction, collections do not implement any kind of structure.

      Cursor – This is a pointer to the result set of a query. The client can iterate through a cursor to get the result.

      Database – It is a container for collections like RDBMS in that it is a container for tables. Each database gets its own set of files on the file system. A MongoDB server can store multiple databases.

      Documents – A record in a MongoDB collection is basically called a document. The document, in turn, will contain field names and values.

      Field – a name-value pair in a document. A document has zero or more fields. Fields correspond to columns in a relational database. The following diagram shows an example of a field containing key value pairs. So in the example below CustomerID and 11 are one of the key value pairs defined in the document.

      JSON – This is known as JavaScript Object Notation. It is a human-readable, plain text format for expressing structured data. JSON is currently supported in many programming languages.


      Just a quick note on the main difference between the _id field and the normal collection field. The _id field is used to uniquely identify documents in a collection and is automatically added by MongoDB when the collection is created.


      Why Use MongoDB?

      Some of the reasons why one should start using MongoDB are mentioned below:

      Document-oriented – Since MongoDB is a NoSQL type of database, instead of keeping the data in a relational type of format, it stores the data in documents. This makes MongoDB very flexible and adaptable to real business world situations and requirements.


      Ad-hoc queries – MongoDB supports search by field, range queries and regular expression searches. Queries can be made to return specific fields within documents.


      Indexing – Indexes can be created to improve the performance of searches within MongoDB. Any field in a MongoDB document can be indexed.


      Replication – MongoDB can provide high availability with replica sets. A replica set consists of two or more MongoDB instances. Each replica set member can act as a primary or secondary replica at any time. The primary replica is the main server that interacts with the client and performs all read/write operations. Secondary replicas maintain a copy of the primary’s data using the underlying replication. When a primary replica fails, the replica set automatically switches to the secondary and then it becomes the primary server.


      Load Balancing – MongoDB uses the concept of sharding to scale horizontally by splitting the data across multiple MongoDB instances. MongoDB can run on multiple servers, balancing load and/or duplicate data to keep the system up and running in case of hardware failure.


      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: Here the “pretty()” query method is used only for better readability of the document database. (it’s not necessary)


      Course Curriculum

      Develop Your Skills with MongoDB Certification Training

      Weekday / Weekend BatchesSee Batch Details

      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.


      • 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”}}

      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

      • > 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
      • ,
      • ,

      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.

      • 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”)

      MongoDB pros and cons:

    • 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 Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

      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.


    Are you looking training with Right Jobs?

    Contact Us

    Popular Courses

    Get Training Quote for Free