MongoDB find() With Examples

There are two ways to find an item from the MongoDB database. One is through MongoDB find method and the other is through findOne method. Let’s go through find() method first from the shell and later through a Java program.

MongoDB find()

MongoDB find method fetches the document in a collection and returns the cursor for the documents matching the criteria requested by the user.

The syntax for mongodb find() method is as follows db.collection.find(<criteria>,<projection>)
.

criteria: field specifies the selection criteria entered by the user.

projection: specifies the fields returned using projection operators.

Projection operators can be any of the following.

  1. $: first element that matches the condition.
  2. $elemMatch: first element that matches the criteria specified in elem condition.
  3. $slice: limits the number of elements in an array.
  4. $meta: document score assigned during text operation. 
If the projection argument is specified then the cursor returns only projection field and _id field. The _id field can be excluded. By default the first 20 documents will be displayed. The syntax for projection parameter is 
{ field1: <boolean>, field2: <boolean> … }
The boolean values can be 0 or false to exclude the field and 1 or true to include the field. Let us now look at the various ways of putting this into use.

MongoDB find – finding all the documents in the collection


This method returns all the documents present in the database of the specified collection.

For example: db.car.find()

Output:

MongoDB find – fetching the documents that match the given query criteria

This fetches the documents that match the selection criteria specified by the user.

For example: db.car.find( { speed: { $gt:50 } }) 
Fetches documents with speed greater than 50.

Output:

MongoDB find – fetching based on equality of documents

This mongodb find query fetches the document which satisfies the equality condition.


For example: db.car.find( { _id: 3} )

Output:

The document having the value of 3 as id is retrieved.

MongoDB find – fetching document using multiple matching criteria as Query operators

This operation fetches the document using more than one value as criteria specified.


For example db.car.find(
{
_id:{ $in: [3,2]} }).

Output:

The documents having id of values 2 and 3 is fetched using the in operator.

MongoDB find – fetching the document using range operators


This find operation fetches the document having values within the range specified.

For example 
db.car.find( { speed: {$gt:40, $lt:65}})

Output:

The documents whose car’s speed greater than 40 but less than 65 is retrieved.

MongoDB find projection

MongoDB projections are nothing but the fields that we wish to display as a part of the output. There are multiple usages here too.

mongoDB find projection – specifying the fields

This operation displays the fields that are chosen using projection parameter.

For example:
 db.car.find( {speed: {$gt:60} },{name:1,speed:1})

Output:

This operation finds all the documents in the car collection whose speed is greater than 50 and the fields name, speed and id are displayed as specified in the projection parameter.

MongoDB find projection – exclude the fields explicitly

This operation displays all the fields except the field specified in the projection parameter.

For Example 
db.car.find(
{speed:62}, {'mfdcountry':0,cno:0})

Output:

The operation displays all the fields of the collection car having speed of 62 except the fields mfdcountry and cno.

MongoDB find projection – explicitly exclude the _id field

This operation excludes the id field from the returned document.

For example 
db.car.find( {speed: {$gt:65}},{_id:0})

Output:

The car whose speed is greater than 65 is displayed without the _id field.

Iterating on the Cursors returned by MongoDB find

As in other databases, a cursor is returned when there are multiple documents being returned. The returned cursor can be assigned to a variable using var keyword.

For example 
var carcursor = db.car.find();


The next() method can be used by the cursor to access the subsequent documents from the cursor.

Output: “Polo” (or it can be different, based on the first car returned in the next() call)

carcursor.hasNext() returns true since there are many cars which causes carcursor.next() to be executed fetching the first document ( Polo record ) which gets assigned to myCar. myCar is checked for existence and the name is extracted as ‘Polo’.

forEach method usage in cursor of MongoDB find query

The forEach method iterates over the cursor and retrieves all the documents.

In this example, carCursor iterates over all the items since we call forEach on it. The data is converted to json format for better understanding.

mongoDB find sort

The sort() method is used to order the documents.

For example 
db.car.find().sort({name:1})

The sort method orders the car collection by name in ascending order.

MongoDB find – limiting the output

The limit() method is used to restrict the number of documents displayed to the user.

For example 
db.car.find().limit(2);

Output:

The first 2 records will only be displayed to the user as the limit is specified as 2.

MongoDB find skip method

The skip() method specifies the starting point of the result set.

For example 
db.car.find().skip(6)


Output:

The first 6 records will be skipped and the remaining documents will be displayed because the starting point is set as 6

MongoDB find – chaining multiple methods

One or more methods can be combined as shown below.

db.car.find().limit(2).sort({name:1})


Output:

mongoDB find in array

Lets create an array field regno and insert values into it.


Now on performing db.car.find() operation, we can see the newly added regno array fields too.

Execute the following query for fetching arrays:

db.car.find( {regno: {$gt:5, $lt:20}})


Output:

The above 2 records are fetched because 10 is greater than 5 and less than 20 and 11 is greater than 5 but less than 20.

Let us query for finding a particular element in an array:

db.car.find({regno:21})


Output: { “_id” : 17, “regno” : [ 21, 30 ] }
}

MongoDB find java example

Until now, we saw how to perform find operations using the Mongo console. In this section, we will see how to do the same using Java programs.

You can use above program and check the output yourself. That’s all for MongoDB find, we will look into more of MongoDB methods in coming posts.

Reference: Official Doc

By admin

Leave a Reply