Skip to content
Related Articles

Related Articles

What is a MongoDB Query?
  • Last Updated : 08 Feb, 2021

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. It stores data in BSON (Binary JSON) format just like JSON format. 

A simple example of a MongoDB database collection.

{

    “_id” : ObjectId(“6009585d35cce6b7b8f087f1”),

    “title” : “Math”,



    “author” : “Aditya”,

    “level” : “basic”,

    “length” : 230,

    “example” : 11

}

What is MongoDB Query?

MongoDB Query is a way to get the data from the MongoDB database. MongoDB queries provide the simplicity in process of fetching data from the database, it’s similar to SQL queries 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 the function names as db.collection_name.find() to operate query operation on database. In this post, we discussed this function in many ways using different methods and operators. 

Here, we are working with:



Database: geeksforgeeks  

Collection: Article 

Note: Here “pretty()” query method is using for only better readability of Document Database.(It’s not necessary) 

Field selection

The find() method displays the database collection in Non-Structured form({<Key> : <value>}) including auto-created <key> ” id  ” by MongoDB and collection data inserted by user or admin.

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 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 the article collection.

Displaying documents in a formatted way

In MongoDB, we can display documents of the specified collection in well-formatted way using pretty() method. 

Syntax: 

 db.collection_name.find().pretty() 

Example:

db.article.find().pretty() 

Here, we are going to display the documents of the article collection in a well-formatted way using pretty() method.

Equal filter query 

The equality operator($eq) is used to match the 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"}}).pretty()  

Here, we are going to display the documents that matches the filter query(i.e., {author  :  {$eq : “devil”}}) from the article collection.

Greater than filter query   

To get the specific numeric data using conditions like greater than equal or less than equal use the $gte or $lte operator in the find() method. 

Syntax:  

db.collection_name.find({< key > : {$gte : < value >}}) 

or 

db.collection_name.find({< key > : {$lte : < value >}}) 

Example: 

db.article.find({length:{$gte:510}}).pretty()

Here, we are querying to get documented data which has the length attribute value greater than 510. So, we pass a filter query that is {length : {$gte : 510}} in the find() method.

Check the existence filter query

$exists operator shows all the collection documents if they exist on a given key.

Syntax:  

db.collection_name.find({< key > : {$exists : < boolean >}})

Example:  

db.article.find({time:{$exists:"true"}}).pretty()

Here, we are going to look all the documents which has the attribute named as time by passing a filter query that is {time : {$exists : “true”}} in the find() method.

Logical operator query

$and operator comes under the type of MongoDB logical operator which perform logical AND operation on the array of one or more expressions and select or retrieve only those documents that match all the given expression 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 and operator and given two condition which are highlighted following 

  • and operator: {$and : [ first condition, second condition]}
  • first condition(level == “high”): { level : {$eq  :  “high”}}
  • second condition: {level : {$exists : “true”}} 

Project query

This query returned the result whatever we specify in parameter using 1 and 0 

  • 1: It indicated to return the result
  • 0: It indicates to not return the result

These parameters called Projection Parameter

Syntax:  

db. collection_name. find({< key > : < value >}, {<key> : < Projection_Parameter >})

Example: 

db. article. find({author : "devil"},{title : 0}).pretty()

This query example is requesting the data which have the author as named “devil” but in the record don’t want to show the title attribute by specifying it as projection parameter 0

  • Query to find a record having given attribute: { author :  “devil”}
  • Projection Parameter: {title  :  0} 

Limit Query

This query method specifies a maximum number of documents for a cursor to return. 

Syntax : 

db.collection_name.find({< key > : < value >}).limit(< Integer_value >)

Example: 

db. article. find({author : “devil” }). limit(2) . pretty() 

This query method is simply the extension of the find method only provide a result at a maximum limited number(here is 2) 

  • Query to find record having given attribute: find({author : “devil” }) 
  • Query to limit result: limit( 2)

Output

Sort the fields

In MongoDB, It returns the finding result in sorted order that can be ascending or descending. The order specifies by given parameter like 

  • 1 (Positive One): It indicates the Ascending order of having attribute value in the record.
  • -1 (Negative One): It indicates the Descending order of having attribute value in the record.

Syntax:

 db.collection_name.find(). sort({< key > : 1}) 

Example 

db.article.find({author : "devil"}).sort({example :  1}).pretty() 

This Example will show the resultant record which has the example attribute and it will show in ascending order because here we are passing value 1.

  • Query to finding record having given attribute: find ({author : “devil”})
  • Query to sort parameter: sort({example : 1}) 

My Personal Notes arrow_drop_up
Recommended Articles
Page :