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.
- $: first element that matches the condition.
- $elemMatch: first element that matches the criteria specified in elem condition.
- $slice: limits the number of elements in an array.
- $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:
1 2 3 4 5 6 7 8 9 10 11 |
<span style="color: #008000;"><strong><code> { "_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" } </code></strong></span> |
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:
1 2 3 4 5 6 7 |
<span style="color: #008000;"><strong><code> { "_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" } </code></strong></span> |
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:
1 2 3 |
<span style="color: #008000;"><strong><code>
{ "_id" : 3, "name" : "Audi", "color" : "Black", "cno" : "H412", "speed" : 50, "mfdcountry" : "Germany" } </code></strong></span> |
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:
1 2 3 4 |
<span style="color: #008000;"><strong><code> { "_id" : 2, "name" : "Polo", "color" : "White", "cno" : "H411", "speed" : 45, "mfdcountry" : "Japan" }
{ "_id" : 3, "name" : "Audi", "color" : "Black", "cno" : "H412", "speed" : 50, "mfdcountry" : "Germany" } </code></strong></span> |
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:
1 2 3 4 5 6 |
<span style="color: #008000;"><strong><code>
{ "_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" } </code></strong></span> |
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:
1 2 3 4 |
<span style="color: #008000;"><strong><code>
{ "_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 } </code></strong></span> |
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:
1 2 3 |
<span style="color: #008000;"><strong><code>
{ "_id" : ObjectId("546cc76093f404729e2e946e"), "name" : "Volkswagen", "color" : "JetBlue", "speed" : 62 } </code></strong></span> |
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:
1 2 3 4 5 6 |
<span style="color: #008000;"><strong><code> { "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" } </code></strong></span> |
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.
1 2 3 4 5 |
>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.
1 2 3 4 |
>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:
1 2 3 4 |
{ "_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:
1 2 3 4 5 |
{ "_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:
1 2 3 4 |
"_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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
> 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:
1 2 3 4 |
{ "_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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 |
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