MongoDB - Day 8 (Find Method Part 2)

Before reading this article, I highly recommend reading the following previous parts of the series: 

In the previous article we learned some basic operations and uses of the find method. Today we learn some advanced things about the find method. If you haven't read my previous article related to the find method then please read that first.

Now we start this article.

First we create a “Post” Collection and insert some data into this collection.

data into this Collection

Now fetch data from the “Post” collection using the find method. The structure of the Post collection will be as in the following:

Post

Projection

Projection means selecting only the necessary data rather than selecting all the data of a document. As I explained in the previous article, the find method takes two parameters. The first is a “Select Query” and the second is the “Projection“. The Projection parameter returns the specific fields of the document rather than all the fields. It is an optional parameter. If we don't specify this parameter then MongoDB will return all the fields of the document.

Syntax: { Field1:<Boolean>,Field2:<Boolean>……….. Fieldn:<Boolean> }

The selection criteria depends upon the <Boolean> value as in the following:

  • 1 or true means the field will be included in the document.
  • 0 or false means the field will be excluded from the document.

Note:

  • The _id field of any document is implicitly included even if 1 or true is not specified for this. If you want to remove the _id field from the selected document field then specify 0 or false for the _id field. For a better understanding we explain this concept later in this article.

  • A projection cannot contain both include and exclude specifications, except for the exclusion of the _id field. In other words either a projection contains 0 for all fields or 1. It can't happen that some fields in the projection contains 0 and the other fields contain 1 at the same time.

Now we perform some query to understand the concept of projection.

Query 1: Select _id, PostBy ,Title fields for each Post.

Output

perform some query

In the preceding example we include the required fields.

We can retrieve the same result by excluding all the fields that are not required.

retrieve same result

In the previous query we use the projection {PostBy:1, Title: 1}. We don't include the “_id” field of the document but we can see that “_id” is present in the result . Because the “_id” field of a document is implicitly included even if it is not specified 1 or true for this. If you want to remove the “_id” field from the selected document field then specify 0 or false for the “_id” field.

Example

filed from selected document

As we explained iin the preceding a projection cannot contain both include and exclude specifications except for the exclusion of the _id field. If we try to do so then MongoDB will throw an error that “projection can't have a mix of inclusion and exclusion”.

Let us see an example as in the following:

Let us take an example

In the preceding query we try to exclude the “PostBy” field and include the “Title” field, so MongoDB throws an error.

Create Range for Query

In the previous article we learned some conditional operators. $gt(greater than) and $lt(less than) both are conditional operators. Combining the use of both operators work as a range. So if we want to generate a range for a specific field then we can use $lt and $gt conditional operators.

Syntax: db.Collection_Name.find( { Field_Name: { $gt:value, $lt:value}})

Let us see an example.

Query: Select Title, Tags and Likes of all the posts that have Likes more than 4 and less than 7.

Output

Select Title

Use Variable Name

We know that the find method returns a cursor to the selected documents. So we can save this cursor into a variable and print the documents.

Example

print the documents

Use DBQuery.shellBatchSize

The find method returns a cursor to the selected result. If we don't assign this cursor to a variable then MongoDB prints the top 20 results automatically. We can use an “it” command to continue to iterate the cursor. We can use the DBQuery.shellBatchSize to change the number of iterations.

Example

shellBatchSize

In the preceding example we assign the value of DBQuery.shellBatchSize equal to two. If we want to print the next two values than we can use the “it” command.

DBQuery

We can also use the DBQuery.shellBatchSize command with a variable.

Use forEach Loop with Cursor

Use forEach Loop with Cursor

We can use a forEach loop with a cursor variable to iterate the cursor and access the documents.

Example

cursor variable

Here the “printjson” option is used to print the data of a cursor in JSON format.

Use next() method with Cursor

Next is a cursor method. We can use the next method to retrieve the result from the cursor one by one. The next method returns the next document from a cursor (or cursor variable).

Let us see an example as in the following:

example

In the preceding example, in the first step we store the cursor value into a variable. hasNext is also a cursor method to check the next value of the cursor. The Next() method retrieves the next value from the cursor. The Print(tojson()) method prints the data in JSON format.

We can print the specific field of a document from the selected cursor using the ”.” operator.

Let us see an example as in the following:

printjson

We can use the printjson() method instead of print(tojson()). The Printjson() method prints the data in JSON format. I suggest using the printjson() method instead of the print(tojson()) method.

element in their Tags Array

Query for Array Element

The following query will return the result on the behalf of an element of an Array. In the “Post” collection each document has a “Tags” array. This array contains some elements. Now we return the result on the basis of an Array element.

Query: Select the name of all the posts containing a “SQL” element in their Tags array.

Output

CommentBy

Query for Embedded Document

The following query will return the result for all documents that contain a comment array and the array contains an embedded document and the value of the “CommentBy” field of the embedded document is equal to “Rahul”.

We have various methods for the embedded document. We will explain each method.

Method 1: Using $elemMatch

elemMatch

Method 2: Using “.” Dot notation

Syntax: db.Collection_Name.find({“Field_Name.ED_FiledName” : Value } )

Here ED= Embedded Document

Embedded Document

Method 3: Exact Match

This method will return a result when the query successfully matches the value of all fields of the embedded document.

document

If we neglect any single field or any value of the embedded document field doesn't match the value of the query then MongoDB will not display any result. Let us try to remove the “Text” field from the previous query and examine the result.

result

So it is necessary that we provide the value of all fields in the exact matching method.

Conditional Operator for Field That contain Array

If a field contains an array and the select query contains multiple conditional operators then if a single element of an array meets the condition of all the conditional operators then MongoDB will return the entire array.

Let see an example.

Assume we have the following collection.

collection

Now we apply the following query for this collection.

db.Test.find( { Value: { $gt:15 , $lt:20 } } ).pretty()


Output

Output

Today we learned some advanced commands for the find method. In the next article we learn more about the find method.

Thanks for reading this article.