MongoDB find()

Filed Under: MongoDB

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:


{ "_id" : 2, "name" : "Polo", "color" : "White", "cno" : "H411", "speed" : 45, "mfdcountry" : "Japan" }
{ "_id" : 3, "name" : "Audi", "color" : "Black", "cno" : "H412", "speed" : 50, "mfdcountry" : "Germany" }
{ "_id" : ObjectId("546c7c7d6be0faf69ee36546"), "name" : "WagonR", "speed" : 5, "color" : "Blue" }
{ "_id" : ObjectId("546c9f347256eabc40c9da1c"), "cno" : "Silver", "color" : "Silver", "name" : "HondaCity", "speed" : 45 }
{ "_id" : ObjectId("546cb92393f464ed49d620db"), "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "_id" : ObjectId("546cb9c293f4d93688ebaff6"), "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "_id" : ObjectId("546cc38393f4c76a29a36021"), "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "_id" : ObjectId("546cc3ad93f48e6185bffb0d"), "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "_id" : ObjectId("546cc76093f404729e2e946e"), "name" : "Volkswagen", "color" : "JetBlue", "cno" : "H672", "speed" : 62, "mfdcountry" : "Italy" }

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:


{ "_id" : ObjectId("546cb92393f464ed49d620db"), "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "_id" : ObjectId("546cb9c293f4d93688ebaff6"), "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "_id" : ObjectId("546cc38393f4c76a29a36021"), "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "_id" : ObjectId("546cc3ad93f48e6185bffb0d"), "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "_id" : ObjectId("546cc76093f404729e2e946e"), "name" : "Volkswagen", "color" : "JetBlue", "cno" : "H672", "speed" : 62, "mfdcountry" : "Italy" }

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:



{ "_id" : 3, "name" : "Audi", "color" : "Black", "cno" : "H412", "speed" : 50, "mfdcountry" : "Germany" }

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:


{ "_id" : 2, "name" : "Polo", "color" : "White", "cno" : "H411", "speed" : 45, "mfdcountry" : "Japan" }

{ "_id" : 3, "name" : "Audi", "color" : "Black", "cno" : "H412", "speed" : 50, "mfdcountry" : "Germany" }

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:



{ "_id" : 2, "name" : "Polo", "color" : "White", "cno" : "H411", "speed" : 45, "mfdcountry" : "Japan" }

{ "_id" : 3, "name" : "Audi", "color" : "Black", "cno" : "H412", "speed" : 50, "mfdcountry" : "Germany" }
{ "_id" : ObjectId("546c9f347256eabc40c9da1c"), "cno" : "Silver", "color" : "Silver", "name" : "HondaCity", "speed" : 45 }
{ "_id" : ObjectId("546cc76093f404729e2e946e"), "name" : "Volkswagen", "color" : "JetBlue", "cno" : "H672", "speed" : 62, "mfdcountry" : "Italy" }

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:



{ "_id" : ObjectId("546cb92393f464ed49d620db"), "name" : "Zen", "speed" : 67 } { "_id" : ObjectId("546cb9c293f4d93688ebaff6"), "name" : "Zen", "speed" : 67 }
{ "_id" : ObjectId("546cc38393f4c76a29a36021"), "name" : "Zen", "speed" : 67 }
{ "_id" : ObjectId("546cc3ad93f48e6185bffb0d"), "name" : "Zen", "speed" : 67 }
{ "_id" : ObjectId("546cc76093f404729e2e946e"), "name" : "Volkswagen", "speed" : 62 }

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:



{ "_id" : ObjectId("546cc76093f404729e2e946e"), "name" : "Volkswagen", "color" : "JetBlue", "speed" : 62 }

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:


{ "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }

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.


>var carcursor = db.car.find();

>var myCar = carcursor.hasNext() ? carcursor.next():null;
>if (myCar) {
var carName = myCar.name; print (tojson(carName));}

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.


>var carCursor = db.car.find();
>carCursor.forEach(printjson);

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:


{ "_id" : 2, "name" : "Polo", "color" : "White", "cno" : "H411", "speed" : 45, "mfdcountry" : "Japan" }

{ "_id" : 3, "name" : "Audi", "color" : "Black", "cno" : "H412", "speed" : 50, "mfdcountry" : "Germany" }

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:


{ "_id" : ObjectId("546cc38393f4c76a29a36021"), "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "_id" : ObjectId("546cc3ad93f48e6185bffb0d"), "name" : "Zen", "color" : "JetRed", "cno" : "H671", "speed" : 67, "mfdcountry" : "Rome" }
{ "_id" : ObjectId("546cc76093f404729e2e946e"), "name" : "Volkswagen", "color" : "JetBlue", "cno" : "H672", "speed" : 62, "mfdcountry" : "Italy" }

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:


"_id" : 3, "name" : "Audi", "color" : "Black", "cno" : "H412", "speed" : 50, "mfdcountry" : "Germany" }
{ "_id" : ObjectId("546c9f347256eabc40c9da1c"), "cno" : "Silver", "color" : "Silver", "name" : "HondaCity", "speed" : 45 }

mongoDB find in array

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


> db.car.insert(
... [{_id:15, "regno":[5,10]},
... {_id:16, "regno":[11,20]},
... {_id:17, "regno":[21,30]}])
BulkWriteResult({
	"writeErrors" : [ ],
	"writeConcernErrors" : [ ],
	"nInserted" : 3,
	"nUpserted" : 0,
	"nMatched" : 0,
	"nModified" : 0,
	"nRemoved" : 0,
	"upserted" : [ ]
})
> 


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:



{ "_id" : 15, "regno" : [ 5, 10 ] }
{ "_id" : 16, "regno" : [ 11, 20 ] }

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.


package com.journaldev.mongodb;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

public class MongoDBFindOperations {

	// method that retrieves all the documents present in the database without
	// any criteria
	public static void findAll() throws UnknownHostException {

		// Get a new connection to the db assuming that it is running
		MongoClient mongoClient = new MongoClient("localhost");

		// //use test as a datbase,use your database here
		DB db = mongoClient.getDB("test");

		// //fetch the collection object ,car is used here,use your own
		DBCollection coll = db.getCollection("car");

		// //invoking find() method and storing the result in carCursor
		DBCursor carCursor = coll.find();

		// printing the cursor contents
		try {
			while (carCursor.hasNext()) {
				System.out.println(carCursor.next());
			}
		} finally {
			carCursor.close();// close the cursor
		}
	}
	
	// method to retrieve documents based on the selection criteria
	public static void findBYCriteria() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");

		// criteria specified as speed greater than 50
		DBObject query = new BasicDBObject("speed",
				new BasicDBObject("$gt", 50));
		// /result stored in cursor using find() method
		DBCursor carCursor1 = col.find(query);
		System.out
				.println("­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­");
		try {
			while (carCursor1.hasNext()) {
				System.out.println(carCursor1.next());
			}
		} finally {
			carCursor1.close();
		}
	}
	
	public static void findByEquality() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");

		// criteria with id 3 is specified
		DBObject query = new BasicDBObject("_id", 3);
		DBCursor c1 = col.find(query);
		System.out
				.println("­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­");
		try {
			while (c1.hasNext()) {
				System.out.println(c1.next());
			}
		} finally {
			c1.close();
		}
	}
	
	public static void findByQueryOperators() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");

		// criteria with speed greater than 40 and less than 65
		DBObject query = new BasicDBObject("speed",
				new BasicDBObject("$gt", 40).append("$lt", 65));
		DBCursor carCursor1 = col.find(query);
		System.out
				.println("­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­");
		try {
			while (carCursor1.hasNext()) {
				System.out.println(carCursor1.next());
			}
		} finally {
			carCursor1.close();
		}
	}
	
	public static void findByfields() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");

		DBObject query = new BasicDBObject("speed",
				new BasicDBObject("$gt", 60));
		// fields with name and speed field is specified and only these fields
		// are displayed
		BasicDBObject fields = new BasicDBObject("name", 1).append("speed", 1);
		DBCursor carCursor1 = col.find(query, fields);
		System.out
				.println("­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­");
		try {
			while (carCursor1.hasNext()) {
				System.out.println(carCursor1.next());
			}
		} finally {
			carCursor1.close();
		}
	}
	
	public static void excludeByfields() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");

		DBObject query = new BasicDBObject("speed",
				new BasicDBObject("$gt", 65));
		// excluding mfdcountry and cno fields by setting to 0
		BasicDBObject fields = new BasicDBObject("mfdcountry", 0).append("cno",
				0);
		DBCursor carCursor1 = col.find(query, fields);
		System.out
				.println("­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­");
		try {
			while (carCursor1.hasNext()) {
				System.out.println(carCursor1.next());
			}
		} finally {
			carCursor1.close();
		}
	}
	
	public static void excludeByIdfield() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");

		DBObject query = new BasicDBObject("speed",
				new BasicDBObject("$gt", 65)); // excluding id field by setting
												// to 0
		BasicDBObject fields = new BasicDBObject("_id", 0);
		DBCursor carCursor1 = col.find(query, fields);
		System.out
				.println("­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­");
		try {
			while (carCursor1.hasNext()) {
				System.out.println(carCursor1.next());
			}
		} finally {
			carCursor1.close();
		}
	}

	public static void sortMongodb() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");
		DBCursor carCursor = col.find();
		// sort the car collection in ascending order
		carCursor.sort(new BasicDBObject("name", 1));
		
		try {
			while (carCursor.hasNext()) {

				System.out.println(carCursor.next());
			}
		} finally {
			carCursor.close();
		}
	}
	
	public static void limitMongodb() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");
		// limits to only 2 records
		DBCursor carCursor = col.find().limit(2);
		
		try {
			while (carCursor.hasNext()) {

				System.out.println(carCursor.next());
			}
		} finally {
			carCursor.close();
		}
	}
	
	public static void skipMongodb() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");
		// skips the first 10 records
		DBCursor carCursor = col.find().skip(10);
		System.out
				.println("­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­");
		try {
			while (carCursor.hasNext()) {

				System.out.println(carCursor.next());
			}
		} finally {
			carCursor.close();
		}
	}
	
	public static void sortLimitMongodb() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");
		DBCursor carCursor = col.find();
		// combining sort and limit methods
		carCursor.sort(new BasicDBObject("name", 1)).limit(2);
		System.out
				.println("­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­");
		try {
			while (carCursor.hasNext()) {
				System.out.println(carCursor.next());
			}
		} finally {
			carCursor.close();
		}
	}
	
	public static void insertArray() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car"); // regno array is declared
		List<Integer> regno = new ArrayList<Integer>();
		// adding values to regno field
		regno.add(31);
		regno.add(41);
		regno.add(65);
		regno.add(75);
		// setting regno to new object b1
		BasicDBObject b1 = new BasicDBObject("regno", regno);
		// inserting b1 to collection col
		col.insert(b1);
		DBCursor c3 = col.find();
		try {
			while (c3.hasNext()) {
				System.out.println(c3.next());
			}
		} finally {
			c3.close();
		}
	}
	
	public static void queryArray() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");

		// querying for array values greater than 31 and less than 65
		DBObject query = new BasicDBObject("regno",
				new BasicDBObject("$gt", 31).append("$lt", 65));
		DBCursor c1 = col.find(query);
		try {
			while (c1.hasNext()) {
				System.out.println(c1.next());
			}
		} finally {
			c1.close();
		}
	}
	
	public static void queryArrayElement() throws UnknownHostException {
		MongoClient m1 = new MongoClient("localhost");
		DB db = m1.getDB("test");
		DBCollection col = db.getCollection("car");

		// quering for regno 75
		DBObject query = new BasicDBObject("regno", 75);
		DBCursor c1 = col.find(query);
		
		try {
			while (c1.hasNext()) {
				System.out.println(c1.next());
			}
		} finally {
			c1.close();
		}
	}

}

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

Comments

  1. Hitesh Kumar says:

    How to get datatypes of whole collections?
    For exapmle:
    { “name” : “Bob4” , “age” : 192.0}, { “name” : “Bob5” , “age” : 192.0}

    name= String
    age=int

    Suppose you don’t number of fields in document and you have to find datatype of every field.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages