MongoDB Query Document Using Find() With Example

Read it in 8 Mins

Last updated on
20th Jan, 2022
Published
20th Jan, 2022
Views
6,535
MongoDB Query Document Using Find() With Example

MongoDB's find() method selects documents from a collection or view and returns a cursor to those documents. There are two parameters in this formula: query and projection.

Query – This is an optional parameter that specifies the criteria for selection. In simple terms, a query is what you want to search for within a collection.

Projection – This is an optional parameter that specifies what should be returned if the query criteria are satisfied. In simple terms, it is a type of decision-making that is based on a set of criteria.

MongoDB's Flexible Schema

A NoSQL database, which stands for "not only SQL," is a way of storing and retrieving data that is different from relational databases' traditional table structures (RDBMS).

When storing large amounts of unstructured data with changing schemas, NoSQL databases are indeed a better option than RDBMS. Horizontal scaling properties of NoSQL databases allow them to store and process large amounts of data.

These are intended for storing, retrieving, and managing document-oriented data, which is frequently stored in JSON format (JavaScript Object Notation). Document databases, unlike RDBMSs, have a flexible schema that is defined by the contents of the documents.

MongoDB is one of the most widely used open-source NoSQL document databases. MongoDB is known as a 'schemaless' database because it does not impose a specific structure on documents in a collection.

MongoDB is compatible with a number of popular programming languages. It also offers a high level of operational flexibility because it scales well horizontally, allowing data to be spread or 'sharded' across multiple commodity servers with the ability to add more servers as needed. MongoDB can be run on a variety of platforms, including developer laptops, private clouds, and public clouds.

Querying documents using find()

MongoDB queries are used to retrieve or fetch data from a MongoDB database. When running a query, you can use criteria or conditions to retrieve specific data from the database.

The function db.collection is provided by MongoDB. find() is a function that retrieves documents from a MongoDB database.

In MongoDB, the find method is used to retrieve a specific document from the MongoDB collection. In Mongo DB, there are a total of six methods for retrieving specific records.

  • find()
  • findAndModify()
  • findOne()
  • findOneAndDelete()
  • findOneAndReplace()
  • findOneAndUpdate()

Syntax:

find(query, projection)

We can fetch a specific record using the Find method, which has two parameters. If these two parameters are omitted, the find method will return all of the documents in the MongoDB collection.

Example:

Consider an example of employees with the database of employee_id and employee_name and we will fetch the documents using find() method.

First, create a database with the name “employees” with the following code:

use employees

Now, create a collection “employee” with:

db.createCollection("employee")

In the next step we will insert the documents in the database:

db.employee.insert([{employee_id: 101, employee_name: "Ishan"}, {employee_id: 102, employee_name: "Bhavesh"}, {employee_id: 103, employee_name: "Madan"}])

Find all Documents:

To get all the records in a collection, we need to use the find method with an empty parameter. In other words, when we need all the records, we will not use any parameters.

db.employee.find()

Output in Mongo Shell

MongoDB Query Document using find() with Example

The pretty() method can be used to display the results in a formatted manner.

Syntax:

db.COLLECTION_NAME.find().pretty()

Let’s check our documents with pretty() method:

MongoDB Query Document using find() with Example

Query Filters

We will see examples of query operations using the db.collection.find() method in mongosh.

We will use the employee collection in the employees database.

db.employee.insert([{employee_id: 101, employee_name: "Ishan", age: 21, email_id: "ishanjain@gmail.com"}, {employee_id: 102, employee_name: "Bhavesh", age: 22, email_id: "bhaveshg@gmail.com"}, {employee_id: 103, employee_name: "Madan", age: 23, email_id: "madan@gmail.com"}])

As we have seen earlier that to select all the documents in the database we pass an empty document as the query filter parameter to the find method.

db.employee.find().pretty()

MongoDB Query Document using find() with Example

Find the first document in a collection:

db.employee.findOne()

MongoDB Query Document using find() with Example

Find a document by ID:

db.employee.findOne({_id : ObjectId("61d1ae0b56b92c20b423a5a7")})

MongoDB Query Document using find() with Example

Find Documents that Match Query Criteria

db.employee.find({“age”: “22”})

MongoDB Query Document using find() with Example

db.employee.find({"employee_name": "Madan"}).pretty()

MongoDB Query Document using find() with Example

Sort Results by a Field:

db.employee.find().sort({age: 1}).pretty()

order by age, in ascending order

MongoDB Query Document using find() with Example

db.employee.find().sort({age: -1}).pretty()

order by age, in descending order

MongoDB Query Document using find() with Example

AND Conditions:

A compound query can specify conditions for multiple fields in the documents in a collection. A logical AND conjunction connects the clauses of a compound query indirectly, allowing the query to select all documents in the collection that meet the specified conditions.

In the following example, we will consider all the documents in the employee collection where employee_id equals 101 and age equals 21.

db.employee.find({"employee_id": 101, "age": "21" }).pretty()

MongoDB Query Document using find() with Example

Querying nested fields

The embedded or nested document feature in MongoDB is a useful feature. Embedded documents, also known as nested documents, are documents that contain other documents.

You can simply embed a document inside another document in MongoDB. Documents are defined in the mongo shell using curly braces (), and field-value pairs are contained within these curly braces.

Using curly braces, we can now embed or set another document inside these fields, which can include field-value pairs or another sub-document.

Syntax:

{ field: { field1: value1, field2: value2 } }

Example:

We have a database “nested” and in this database we have collection “nesteddoc”.

The following documents will insert into the nesteddoc collection.

db.nesteddoc.insertMany([ { "_id" : 1, "dept" : "A", "item" : { "sku" : "101", "color" : "red" }, "sizes" : [ "S", "M" ] }, { "_id" : 2, "dept" : "A", "item" : { "sku" : "102", "color" : "blue" }, "sizes" : [ "M", "L" ] }, { "_id" : 3, "dept" : "B", "item" : { "sku" : "103", "color" : "blue" }, "sizes" : "S" }, { "_id" : 4, "dept" : "A", "item" : { "sku" : "104", "color" : "black" }, "sizes" : [ "S" ] } ])

Place the documents in the collection now. Also, take a look at the results:

MongoDB Query Document using find() with Example

As a result, the nesteddoc collection contains four documents, each of which contains nested documents. The find() method can be used to access the collection's documents.

db.nesteddoc.find()

MongoDB Query Document using find() with Example

Specify Equality Condition:

In this example, we will select the document from the nesteddoc query where dept equals “A”.

db.nesteddoc.find({dept: "A"})

MongoDB Query Document using find() with Example

Querying Arrays

Use the query document {<field>: <value>} to specify an equality condition on an array, where <value> is the exact array to match, including the order of the elements.

The following query looks for all documents where the field tags value is an array with exactly two elements, "S" and "M," in the order specified:

db.nesteddoc.find( { sizes: ["S", "M"] } )

MongoDB Query Document using find() with Example

Use the $all operator to find an array that contains both the elements "S" and "M," regardless of order or other elements in the array:

db.nested.find( { sizes: { $all: ["S", "M"] } } )

MongoDB Query Document using find() with Example

Query an Array for an Element:

The following example queries for all documents where size is an array that contains the string “S” as one of its elements:

db.nesteddoc.find( { sizes: "S" } )

MongoDB Query Document using find() with Example

Filter conditions

To discuss the filter conditions, we will consider a situation that elaborates this. We will start by creating a collection with the name “products” and then add the documents to it.

db.products.insertMany([
{ _id: 1, item: { name: "ab", code: "123" }, qty: 15, tags: [ "A", "B", "C" ] },
{ _id: 2, item: { name: "cd", code: "123" }, qty: 20, tags: [ "B" ] },
{ _id: 3, item: { name: "ij", code: "456" }, qty: 25, tags: [ "A", "B" ] },
{ _id: 4, item: { name: "xy", code: "456" }, qty: 30, tags: [ "B", "A" ] },
{ _id: 5, item: { name: "mn", code: "000" }, qty: 20, tags: [ [ "A", "B" ], "C" ] }])

To check the documents, use db.products.find():

MongoDB Query Document using find() with Example

$gt

$gt selects documents with a field value greater than (or equal to) the specified value.

db.products.find( { qty: { $gt: “20” } } )

MongoDB Query Document using find() with Example

$gte:

$gte finds documents in which a field's value is greater than or equal to (i.e. >=) a specified value (e.g. value.)

db.products.find( { qty: { $gte: 20 } } )

MongoDB Query Document using find() with Example

$lt:

$lt selects documents whose field value is less than (or equal to) the specified value.

db.products.find( { qty: { $lt: 25 } } )

MongoDB Query Document using find() with Example

$lte:

$lte selects documents in which the field's value is less than or equal to (i.e. =) the specified value.

db.products.find( { qty: { $lte: 20 } } )

MongoDB Query Document using find() with Example

Query an Array by Array Length:

To find arrays with a specific number of elements, use the $size operator. For example, the following selects documents with two elements in the array.

db.products.find( { "tags": {$size: 2} } )

MongoDB Query Document using find() with Example

Projection

In MongoDB, projection refers to selecting only the data that is required rather than the entire document's data. If a document has five fields and you only want to show three of them, select only three of them.

The find() method in MongoDB accepts a second optional parameter, which is a list of fields to retrieve, as explained in MongoDB Query Document. When you use the find() method in MongoDB, it displays all of a document's fields. To prevent this, create a list of fields with the values 1 or 0. The value 1 indicates that the field should be visible, while 0 indicates that it should be hidden.

Syntax:

db.COLLECTION_NAME.find({},{KEY:1})

Example:

We will consider the previous example of products collection. Run the below command on mongoshell to learn how projection works:

db.products.find({},{"tags":1, _id:0})

MongoDB Query Document using find() with Example

Keep in mind that the _id field is always displayed while executing the find() method; if you do not want this field to be displayed, set it to 0.

Optimized Findings

  • To retrieve a document from a MongoDB collection, use the Find method.
  • Using the Find method, we can retrieve specific documents as well as the fields that we require. Other find methods can also be used to retrieve specific documents based on our needs.
  • By inserting array elements into the query, we can retrieve specific elements or documents. To retrieve data for array elements from the collection in MongoDB, we can use multiple query operators.
Profile

Abhresh Sugandhi

Author

Abhresh is specialized as a corporate trainer, He has a decade of experience in technical training blended with virtual webinars and instructor-led session created courses, tutorials, and articles for organizations. He is also the founder of Nikasio.com, which offers multiple services in technical training, project consulting, content development, etc.