MongoDB

How to query in MongoDB

MongoDB is a NoSQL database that supports various methods to store and retrieve data like other databases. MongoDB stores data in the form of documents and once the document is created in a collection; you can retrieve data using MongoDB queries. The retrieving pattern of MongoDB is the same as any SQL database, but the syntax is different. To retrieve information the “.find()” method is used in MongoDB.

In this article, we will provide an insight into MongoDB queries to get the required data from MongoDB databases. This guide comprises several sections to help in querying a document from MongoDB.

Before digging into depth, let’s have a look at the prerequisites to query documents in MongoDB:

Prerequisites

The following things must be present on your Ubuntu system to fetch data from MongoDB-based databases:

Mongo Shell: Mongo shell must be inactive state to execute queries

MongoDB database: A Mongo-based database needs to be on board to apply any operation

How to query document in a MongoDB based database

This section contains the procedural guide to retrieve data from a MongoDB database: The first two steps are required in order to proceed with this guide

Note: You can skip these steps if you have already performed them:

Step 1: Create a Database

Firstly, navigate to mongo shell; you can use the following command to create a database; we have created a database named “test“:

> use test

Text Description automatically generated

Step 2: Create a collection and insert document into the collection

Once database is created, use the following mongo shell command to create a collection; the collection is named “mycollection” here:

> db.createCollection("mycollection")

After creating the collection, insert documents into “mycollection” collection by using insert method:

The following command enables to create two documents in a “mycollection” collection:

> db.mycollection.insert([{"title": "linuxhint", "description": "best linux content provider", "type": "linux"},{"name": "john", "description": "Author at linuxhint", "type": "ubuntu"}])

How to query a document in MongoDB

After performing the above steps you can now apply several MongoDB methods that help to query a document:

How to get all the documents from MongoDB Collection

To retrieve all the documents from a collection; MongoDB supports two methods:

– find(): Finds the documents and displays the result in an unstructured format

– pretty(): Finds the documents and displays the result in a structured format

Both methods are described here with examples:

The “find()” method of MongoDB displays all the documents in a non-structured way; the syntax of this method is written below:

db.[name-of-collection].find()

The “name-of-collection” refers to the collection name from where the document will be retrieved; For instance, the following mongo shell command will help to display all the documents from “mycollection” collection:

> db.mycollection.find()

The “pretty()” method is an extension of the “find()” method and it helps to display a structured format of documents. The syntax of this method is written below:

db.[name-of-collection].find().pretty()

In our case, we have executed the following command to get the documents from “mycollection” collection:

> db.mycollection.find().pretty()

How to get a single document from MongoDB Collection

There is one more method named “findOne()” that helps to retrieve a single document. The syntax of this method is described below:

db.[name-of-collection].findOne()

The command mentioned below will retrieve data from “mycollection” collection of “test” database:

> db.mycollection.findOne()

How to use Mongo supported operators to query a document

Apart from the above methods; you can use several operators that are supported by MongoDB and these operators can be used with the “find()” method to get a more refined form of documents. For instance, the “$eq” operator will print the document that exactly matches our required result; the syntax to use this operator is mentioned below:

{"key":{$eq:"value"}}

Note: to make any operator functional; they are placed inside the “find()” method.

The command mentioned below will display the document that matches the “ubuntu” in type:

> db.mycollection.find({"type":{$eq:"ubuntu"}}).pretty()

Note: The pretty method is just to get the display in a structured format.

The $lt operator: This operator is used in dealing with numeric elements; you can print specific document(s) that falls under the condition: The following syntax is used to apply this operator:

{"key":{$lt:"value"}}

Similarly, there is a list of numeric operators supported by MongoDB:

The $gt operator: This operator displays the document(s) that satisfies the greater than condition: The syntax of the “$gt” operator is described below:

{"key":{$gt:"value"}}

Moreover, few operators ($in and $nin) specifically relate to arrays data type: you can use them to display the document by filtering the content using arrays:

The $in and $nin operators: These both operators are used with the “find()” method to filter documents on basis of arrays:

For instance, $in operator can be used to print the document that matches “key” with any of the indicated “values“:

{"key":{"value":["value1","value2",---]}}

Similarly, the $nin operator finds the document in which “key” does not match the indicated “values“: Syntax of $nin operator is same as $in operator:

{"key":{"value":["value1","value2",---]}}

The OR & AND operators : The OR condition searches for the “key’s” and “value’s” in the collection and print all the documents that consist at least one “key” and associated “value“. The syntax is mentioned below:

{$or:[{key1:value1}, {key2:value2},....]}

Whereas the AND operator matches only those documents that contain all the “keys” and “values” mentioned in the command. The syntax of AND condition is given below:

{$and:[{key1:value1}, {key2:value2}.....]}

Conclusion

MongoDB provides non-relational database management support and acts differently as compared to traditional databases. Like other databases, MongoDB can also query a document with a wide range of methods and operators. In this article, you have learned to query a document in MongoDB using the base methods and operators supported by these methods. The base methods just print the documents without any condition; however, if you want to get the result on a conditional basis; you can use operators with base methods to do so.

About the author

Adnan Shabbir