In this article, we will see some examples of querying MongoDB documents using MongoDB Java API.
All the query APIs work on the collection object, MongoCollection
. A collection object is analogous to a relational database’s table. If you are new to MongoDB, read MongoDB Introduction and Setup for a quick overview.
Before we start with examples, we must first create some sample data.
Insert MongoDB Test Data
We will insert some new products with an embedded seller information.
Document{ { product=Comfi Bunk Bed, finish=Dark walnut, desc=Perfect finish, price=33000, seller={name=Joe Furnirure, street=Baker Street} }, { product=Bed Side Table, finish=Teak, desc=Nice and Simple Design, price=3000, seller={name=Joe Furnirure, street=Baker Street, contact=[[email protected], [email protected]]} }, { product=Study Table, price=10000, seller={name=Joe Furnirure} }, { product=Coffee Table, price=10000, seller={name=Billy Furnirure} }, { product=Study Table, price=20000, seller={name=Sam Furnirure} }, { product=Study Table, price=5000, seller={name=Sam Furnirure} }, { product=Wooden Chair, price=500, seller={name=Joe Furnirure} } }
To insert document we will call one of the insertOne
method on the MongoCollection
object. If you want to insert many documents insertMany
method on the MongoCollection
object. See Inserting Documents using MongoDB Java Driver for more examples.
MongoDBInsertSampleData:
cpackage com.javarticles.mongodb; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import org.bson.Document; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class MongoDBInsertSampleData { public static void main(String[] args) throws UnknownHostException { MongoClient mongoClient = new MongoClient(); try { MongoDatabase database = mongoClient.getDatabase("mydb"); MongoCollection<Document> product = database .getCollection("product"); System.out.println("Drop collection"); product.drop(); System.out.println("Start inserting documents"); List<Document> documentList = new ArrayList<Document>(); documentList.add(new Document("product", "Comfi Bunk Bed") .append("finish", "Dark walnut") .append("desc", "Perfect finish") .append("price", 33000) .append("seller", new BasicDBObject().append("name", "Joe Furnirure") .append("street", "Baker Street"))); BasicDBList emailIds = new BasicDBList(); emailIds.add("[email protected]"); emailIds.add("[email protected]"); documentList.add(new Document("product", "Bed Side Table") .append("finish", "Teak") .append("desc", "Nice and Simple Design") .append("price", 3000) .append("seller", new BasicDBObject().append("name", "Joe Furnirure") .append("street", "Baker Street") .append("contact", emailIds))); documentList.add(new Document("product", "Study Table").append( "price", 10000).append("seller", new BasicDBObject().append("name", "Joe Furnirure"))); documentList.add(new Document("product", "Coffee Table").append( "price", 10000).append("seller", new BasicDBObject().append("name", "Billy Furnirure"))); documentList.add(new Document("product", "Study Table").append( "price", 20000).append("seller", new BasicDBObject().append("name", "Sam Furnirure"))); documentList.add(new Document("product", "Study Table").append( "price", 5000).append("seller", new BasicDBObject().append("name", "Sam Furnirure"))); documentList.add(new Document("product", "Wooden Chair").append( "price", 500).append("seller", new BasicDBObject().append("name", "Sam Furnirure"))); product.insertMany(documentList); System.out.println("Done inserting documents"); } finally { mongoClient.close(); } } }
Output:
Jan 15, 2016 9:53:27 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500} Drop collection Jan 15, 2016 9:53:28 PM com.mongodb.diagnostics.logging.JULLogger log INFO: No server chosen by WritableServerSelector from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=127.0.0.1:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out Jan 15, 2016 9:53:28 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Opened connection [connectionId{localValue:1, serverValue:75}] to 127.0.0.1:27017 Jan 15, 2016 9:53:28 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Monitor thread successfully connected to server with description ServerDescription{address=127.0.0.1:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 0]}, minWireVersion=0, maxWireVersion=4, electionId=null, maxDocumentSize=16777216, roundTripTimeNanos=641252} Jan 15, 2016 9:53:28 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Opened connection [connectionId{localValue:2, serverValue:76}] to 127.0.0.1:27017 Start inserting documents Done inserting documents Jan 15, 2016 9:53:28 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Closed connection [connectionId{localValue:2, serverValue:76}] to 127.0.0.1:27017 because the pool has been closed.
Find All Documents
The most simplest query is to call find()
on MongoCollection
. The returned object is a FindIterable
class which is an Iterable
and one can iterate through it using the foreach.
If you want to iterate using MongoCursor
then call iterator()
on the FindIterable
object. If you have opened the cursor, make sure you close it in the finally.
In the following example, we find all the products inserted so far.
MongoDBFindDocuments:
package com.javarticles.mongodb; import java.net.UnknownHostException; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; public class MongoDBFindDocuments { public static void main(String[] args) throws UnknownHostException { MongoClient mongoClient = new MongoClient(); try { MongoDatabase database = mongoClient.getDatabase("mydb"); MongoCollection<Document> product = database .getCollection("product"); System.out.println("Use Iterable"); for (Document document : product.find()) { System.out.println(document); } System.out.println("Use Iterator"); MongoCursor<Document> cursor = product.find().iterator(); try { while (cursor.hasNext()) { Document document = cursor.next(); System.out.println(document); } } finally { cursor.close(); } } finally { mongoClient.close(); } } }
Output:
Jan 15, 2016 10:06:23 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500} Use Iterable Jan 15, 2016 10:06:23 PM com.mongodb.diagnostics.logging.JULLogger log INFO: No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=127.0.0.1:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out Jan 15, 2016 10:06:23 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Opened connection [connectionId{localValue:1, serverValue:79}] to 127.0.0.1:27017 Jan 15, 2016 10:06:23 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Monitor thread successfully connected to server with description ServerDescription{address=127.0.0.1:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 0]}, minWireVersion=0, maxWireVersion=4, electionId=null, maxDocumentSize=16777216, roundTripTimeNanos=523037} Jan 15, 2016 10:06:23 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Opened connection [connectionId{localValue:2, serverValue:80}] to 127.0.0.1:27017 Document{{_id=56991d004f6d33330886e942, product=Comfi Bunk Bed, finish=Dark walnut, desc=Perfect finish, price=33000, seller=Document{{name=Joe Furnirure, street=Baker Street}}}} Document{{_id=56991d004f6d33330886e943, product=Bed Side Table, finish=Teak, desc=Nice and Simple Design, price=3000, seller=Document{{name=Joe Furnirure, street=Baker Street, contact=[[email protected], [email protected]]}}}} Document{{_id=56991d004f6d33330886e944, product=Study Table, price=10000, seller=Document{{name=Joe Furnirure}}}} Document{{_id=56991d004f6d33330886e945, product=Coffee Table, price=10000, seller=Document{{name=Billy Furnirure}}}} Document{{_id=56991d004f6d33330886e946, product=Study Table, price=20000, seller=Document{{name=Sam Furnirure}}}} Document{{_id=56991d004f6d33330886e947, product=Study Table, price=5000, seller=Document{{name=Sam Furnirure}}}} Document{{_id=56991d004f6d33330886e948, product=Wooden Chair, price=500, seller=Document{{name=Sam Furnirure}}}} Use Iterator Document{{_id=56991d004f6d33330886e942, product=Comfi Bunk Bed, finish=Dark walnut, desc=Perfect finish, price=33000, seller=Document{{name=Joe Furnirure, street=Baker Street}}}} Document{{_id=56991d004f6d33330886e943, product=Bed Side Table, finish=Teak, desc=Nice and Simple Design, price=3000, seller=Document{{name=Joe Furnirure, street=Baker Street, contact=[[email protected], [email protected]]}}}} Document{{_id=56991d004f6d33330886e944, product=Study Table, price=10000, seller=Document{{name=Joe Furnirure}}}} Document{{_id=56991d004f6d33330886e945, product=Coffee Table, price=10000, seller=Document{{name=Billy Furnirure}}}} Document{{_id=56991d004f6d33330886e946, product=Study Table, price=20000, seller=Document{{name=Sam Furnirure}}}} Document{{_id=56991d004f6d33330886e947, product=Study Table, price=5000, seller=Document{{name=Sam Furnirure}}}} Document{{_id=56991d004f6d33330886e948, product=Wooden Chair, price=500, seller=Document{{name=Sam Furnirure}}}} Jan 15, 2016 10:06:23 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Closed connection [connectionId{localValue:2, serverValue:80}] to 127.0.0.1:27017 because the pool has been closed.
Filter Documents
Let’s now apply a filter on the find operation. This is just like appending a WHERE condition to an SQL to filter records. In MongoDB you can filter searches by creating any Bson
object. A Bson
object is one which can be converted to a BSON document, for example, a Document
or a BasicDBObject
. The Bson
document contains set of key/value pairs, we will have to pass it to the find function as an argument.
In the below example, we find ‘Study Table’ from different sellers:
MongoDBFilterDocuments:
package com.javarticles.mongodb; import java.net.UnknownHostException; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class MongoDBFilterDocuments { public static void main(String[] args) throws UnknownHostException { MongoClient mongoClient = new MongoClient(); try { MongoDatabase database = mongoClient.getDatabase("mydb"); MongoCollection<Document> product = database .getCollection("product"); System.out.println("Find Study Tables"); for (Document document : product.find(new Document("product", "Study Table"))) { System.out.println(document); } } finally { mongoClient.close(); } } }
Output:
Jan 16, 2016 1:50:09 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500} Find Study Tables Jan 16, 2016 1:50:09 PM com.mongodb.diagnostics.logging.JULLogger log INFO: No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=127.0.0.1:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out Jan 16, 2016 1:50:09 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Opened connection [connectionId{localValue:1, serverValue:111}] to 127.0.0.1:27017 Jan 16, 2016 1:50:09 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Monitor thread successfully connected to server with description ServerDescription{address=127.0.0.1:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 0]}, minWireVersion=0, maxWireVersion=4, electionId=null, maxDocumentSize=16777216, roundTripTimeNanos=579293} Jan 16, 2016 1:50:09 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Opened connection [connectionId{localValue:2, serverValue:112}] to 127.0.0.1:27017 Document{{_id=5699ac424f6d3348ac3ef610, product=Study Table, price=10000, seller=Document{{name=Joe Furniture}}}} Document{{_id=5699ac424f6d3348ac3ef612, product=Study Table, price=20000, seller=Document{{name=Sam Furniture}}}} Document{{_id=5699ac424f6d3348ac3ef613, product=Study Table, price=5000, seller=Document{{name=Sam Furniture}}}} Jan 16, 2016 1:50:09 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Closed connection [connectionId{localValue:2, serverValue:112}] to 127.0.0.1:27017 because the pool has been closed.
Compound Filter
We saw how to apply simple filter condition ‘product=’Study Table’. If we want to further narrow down the search, we can include multiple keys to the Document
. In the below example, we find ‘Study Tables’ less than 10000.
MongoDBCompoundFilterDocuments:
package com.javarticles.mongodb; import java.net.UnknownHostException; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class MongoDBCompoundFilterDocuments { public static void main(String[] args) throws UnknownHostException { MongoClient mongoClient = new MongoClient(); try { MongoDatabase database = mongoClient.getDatabase("mydb"); MongoCollection<Document> product = database .getCollection("product"); System.out .println("Find Study Tables from 'Sam Furniture', price <=10000"); for (Document document : product .find(new Document("product", "Study Table").append( "price", new Document("$lte", 10000)))) { System.out.println(document); } } finally { mongoClient.close(); } } }
Output:
Jan 16, 2016 1:55:50 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500} Find Study Tables from 'Sam Furniture', price <=10000 Jan 16, 2016 1:55:50 PM com.mongodb.diagnostics.logging.JULLogger log INFO: No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=127.0.0.1:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out Jan 16, 2016 1:55:50 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Opened connection [connectionId{localValue:1, serverValue:113}] to 127.0.0.1:27017 Jan 16, 2016 1:55:50 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Monitor thread successfully connected to server with description ServerDescription{address=127.0.0.1:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 0]}, minWireVersion=0, maxWireVersion=4, electionId=null, maxDocumentSize=16777216, roundTripTimeNanos=424587} Jan 16, 2016 1:55:50 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Opened connection [connectionId{localValue:2, serverValue:114}] to 127.0.0.1:27017 Document{{_id=5699ac424f6d3348ac3ef610, product=Study Table, price=10000, seller=Document{{name=Joe Furniture}}}} Document{{_id=5699ac424f6d3348ac3ef613, product=Study Table, price=5000, seller=Document{{name=Sam Furniture}}}} Jan 16, 2016 1:55:50 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Closed connection [connectionId{localValue:2, serverValue:114}] to 127.0.0.1:27017 because the pool has been closed.
Get the First Document
If we are only interested in the first ‘Study Table’ from the above search results then we need to call first()
on the FindIterable
object returned.
This method returns a single document instead of an iterable object.
MongoDBFirstDocument:
package com.javarticles.mongodb; import java.net.UnknownHostException; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class MongoDBFirstDocument { public static void main(String[] args) throws UnknownHostException { MongoClient mongoClient = new MongoClient(); try { MongoDatabase database = mongoClient.getDatabase("mydb"); MongoCollection<Document> product = database .getCollection("product"); System.out .println("Find Study Tables from 'Sam Furniture', price <=10000, pick the first one"); Document firstDocument = product.find( new Document("product", "Study Table").append("price", new Document("$lte", 10000))).first(); System.out.println(firstDocument); } finally { mongoClient.close(); } } }
Output:
Jan 16, 2016 1:59:18 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500} Find Study Tables from 'Sam Furniture', price <=10000, pick the first one Jan 16, 2016 1:59:18 PM com.mongodb.diagnostics.logging.JULLogger log INFO: No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=127.0.0.1:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out Jan 16, 2016 1:59:18 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Opened connection [connectionId{localValue:1, serverValue:115}] to 127.0.0.1:27017 Jan 16, 2016 1:59:18 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Monitor thread successfully connected to server with description ServerDescription{address=127.0.0.1:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 0]}, minWireVersion=0, maxWireVersion=4, electionId=null, maxDocumentSize=16777216, roundTripTimeNanos=505171} Jan 16, 2016 1:59:18 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Opened connection [connectionId{localValue:2, serverValue:116}] to 127.0.0.1:27017 Document{{_id=5699ac424f6d3348ac3ef610, product=Study Table, price=10000, seller=Document{{name=Joe Furniture}}}} Jan 16, 2016 1:59:18 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Closed connection [connectionId{localValue:2, serverValue:116}] to 127.0.0.1:27017 because the pool has been closed.
Filter using embedded fields
In this example we find all the products from a specific seller ‘Sam Furniture’. The seller information is an embedded document.
You can create a new filter using:
Filters.eq("seller.name", "Sam Furniture")
We can call forEach()
on the iterable object and pass in a function that works on the document object.
For example, a function to print the document as a JSON object that works on each document object returned in the search.
MongoDBFilterOnEmbeddedDoc:
package com.javarticles.mongodb; import java.net.UnknownHostException; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; public class MongoDBFilterOnEmbeddedDoc { public static void main(String[] args) throws UnknownHostException { MongoClient mongoClient = new MongoClient(); try { MongoDatabase database = mongoClient.getDatabase("mydb"); MongoCollection<Document> product = database .getCollection("product"); System.out.println("Find Study Tables from 'Sam Furniture'"); for (Document document : product.find(new Document("product", "Study Table").append("seller.name", "Sam Furniture"))) { System.out.println(document); } product.find(Filters.eq("seller.name", "Sam Furniture")).forEach(new PrintDocumentAsJSON()); } finally { mongoClient.close(); } } }
PrintDocumentAsJSON:
package com.javarticles.mongodb; import org.bson.Document; import com.mongodb.Block; public class PrintDocumentAsJSON implements Block<Document>{ public void apply(Document document) { System.out.println(document.toJson()); } }
Output:
Jan 16, 2016 2:03:45 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500} Find Study Tables from 'Sam Furniture' Jan 16, 2016 2:03:45 PM com.mongodb.diagnostics.logging.JULLogger log INFO: No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=127.0.0.1:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out Jan 16, 2016 2:03:45 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Opened connection [connectionId{localValue:1, serverValue:117}] to 127.0.0.1:27017 Jan 16, 2016 2:03:45 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Monitor thread successfully connected to server with description ServerDescription{address=127.0.0.1:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 0]}, minWireVersion=0, maxWireVersion=4, electionId=null, maxDocumentSize=16777216, roundTripTimeNanos=491488} Jan 16, 2016 2:03:45 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Opened connection [connectionId{localValue:2, serverValue:118}] to 127.0.0.1:27017 Document{{_id=5699ac424f6d3348ac3ef612, product=Study Table, price=20000, seller=Document{{name=Sam Furniture}}}} Document{{_id=5699ac424f6d3348ac3ef613, product=Study Table, price=5000, seller=Document{{name=Sam Furniture}}}} { "_id" : { "$oid" : "5699ac424f6d3348ac3ef612" }, "product" : "Study Table", "price" : 20000, "seller" : { "name" : "Sam Furniture" } } { "_id" : { "$oid" : "5699ac424f6d3348ac3ef613" }, "product" : "Study Table", "price" : 5000, "seller" : { "name" : "Sam Furniture" } } { "_id" : { "$oid" : "5699ac424f6d3348ac3ef614" }, "product" : "Wooden Chair", "price" : 500, "seller" : { "name" : "Sam Furniture" } } Jan 16, 2016 2:03:45 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Closed connection [connectionId{localValue:2, serverValue:118}] to 127.0.0.1:27017 because the pool has been closed.
Filter with Logical Operator
Using Filters
we can construct complex filters. For example, an ‘AND’ operator condition.
Below filter is for finding all ‘Sam Furniture’ less than 10000.
Filters.and(Filters.lte("price", 10000), Filters.eq("seller.name", "Sam Furniture")))
MongoDBFilterWithLogicalOperator:
package com.javarticles.mongodb; import java.net.UnknownHostException; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; public class MongoDBFilterWithLogicalOperator { public static void main(String[] args) throws UnknownHostException { MongoClient mongoClient = new MongoClient(); try { MongoDatabase database = mongoClient.getDatabase("mydb"); MongoCollection<Document> product = database .getCollection("product"); System.out .println("Find all furniture, price <=10000 and furniture shop is 'Sam Furniture'"); for (Document document : product.find(Filters.and(Filters.lte("price", 10000), Filters.eq("seller.name", "Sam Furniture")))) { System.out.println(document); } } finally { mongoClient.close(); } } }
Output:
Jan 16, 2016 2:12:00 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500} Find all furniture, price <=10000 and furniture shop is 'Sam Furniture' Jan 16, 2016 2:12:00 PM com.mongodb.diagnostics.logging.JULLogger log INFO: No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=127.0.0.1:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out Jan 16, 2016 2:12:00 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Opened connection [connectionId{localValue:1, serverValue:119}] to 127.0.0.1:27017 Jan 16, 2016 2:12:00 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Monitor thread successfully connected to server with description ServerDescription{address=127.0.0.1:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 0]}, minWireVersion=0, maxWireVersion=4, electionId=null, maxDocumentSize=16777216, roundTripTimeNanos=420786} Jan 16, 2016 2:12:00 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Opened connection [connectionId{localValue:2, serverValue:120}] to 127.0.0.1:27017 Document{{_id=5699ac424f6d3348ac3ef613, product=Study Table, price=5000, seller=Document{{name=Sam Furniture}}}} Document{{_id=5699ac424f6d3348ac3ef614, product=Wooden Chair, price=500, seller=Document{{name=Sam Furniture}}}} Jan 16, 2016 2:12:00 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Closed connection [connectionId{localValue:2, serverValue:120}] to 127.0.0.1:27017 because the pool has been closed.
Sort Documents
In order to sort the search, call sort()
on FindIterable
object. It sets the sort criteria to apply to the query. The sort criteria can be created using Sorts
class.
Sorts.ascending("price")
In the below example, we find ‘Study Tables’ less than 10000, sorted by price.
MongoDBSortDocuments:
package com.javarticles.mongodb; import java.net.UnknownHostException; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Sorts; public class MongoDBSortDocuments { public static void main(String[] args) throws UnknownHostException { MongoClient mongoClient = new MongoClient(); try { MongoDatabase database = mongoClient.getDatabase("mydb"); MongoCollection<Document> product = database .getCollection("product"); System.out .println("Find Study Tables from 'Sam Furniture', price <=10000, sort by price"); for (Document document : product.find( new Document("product", "Study Table").append("price", new Document("$lte", 10000))).sort( Sorts.ascending("price"))) { System.out.println(document); } } finally { mongoClient.close(); } } }
Output:
Jan 16, 2016 2:14:59 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500} Find Study Tables from 'Sam Furniture', price <=10000, sort by price Jan 16, 2016 2:14:59 PM com.mongodb.diagnostics.logging.JULLogger log INFO: No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=127.0.0.1:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out Jan 16, 2016 2:14:59 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Opened connection [connectionId{localValue:1, serverValue:121}] to 127.0.0.1:27017 Jan 16, 2016 2:14:59 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Monitor thread successfully connected to server with description ServerDescription{address=127.0.0.1:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 0]}, minWireVersion=0, maxWireVersion=4, electionId=null, maxDocumentSize=16777216, roundTripTimeNanos=752245} Jan 16, 2016 2:14:59 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Opened connection [connectionId{localValue:2, serverValue:122}] to 127.0.0.1:27017 Document{{_id=5699ac424f6d3348ac3ef613, product=Study Table, price=5000, seller=Document{{name=Sam Furniture}}}} Document{{_id=5699ac424f6d3348ac3ef610, product=Study Table, price=10000, seller=Document{{name=Joe Furniture}}}} Jan 16, 2016 2:14:59 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Closed connection [connectionId{localValue:2, serverValue:122}] to 127.0.0.1:27017 because the pool has been closed.
Query Projection – Include Fields to Return
If we want to restrict the no. of field in the query, we need to use the projection.
In the below example, we include the fields to return for all matching documents.
Projections.include("seller.name", "product")
Call projection()
on the FindIterable
object and pass in the above projection.
MongoDBProjectionDocuments:
package com.javarticles.mongodb; import java.net.UnknownHostException; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Projections; import com.mongodb.client.model.Sorts; public class MongoDBProjectionDocuments { public static void main(String[] args) throws UnknownHostException { MongoClient mongoClient = new MongoClient(); try { MongoDatabase database = mongoClient.getDatabase("mydb"); MongoCollection<Document> product = database .getCollection("product"); System.out .println("Find furnitures in ascending order of seller name, include seller's name and product"); product.find().sort(Sorts.ascending("seller.name")) .projection(Projections.include("seller.name", "product")) .forEach(new PrintDocumentAsJSON()); } finally { mongoClient.close(); } } }
Output:
Jan 16, 2016 2:19:01 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500} Find furnitures in ascending order of seller name, include seller's name and product Jan 16, 2016 2:19:01 PM com.mongodb.diagnostics.logging.JULLogger log INFO: No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=127.0.0.1:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out Jan 16, 2016 2:19:01 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Opened connection [connectionId{localValue:1, serverValue:125}] to 127.0.0.1:27017 Jan 16, 2016 2:19:01 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Monitor thread successfully connected to server with description ServerDescription{address=127.0.0.1:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 0]}, minWireVersion=0, maxWireVersion=4, electionId=null, maxDocumentSize=16777216, roundTripTimeNanos=522276} Jan 16, 2016 2:19:01 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Opened connection [connectionId{localValue:2, serverValue:126}] to 127.0.0.1:27017 { "_id" : { "$oid" : "5699ac424f6d3348ac3ef611" }, "product" : "Coffee Table", "seller" : { "name" : "Billy Furniture" } } { "_id" : { "$oid" : "5699ac424f6d3348ac3ef60e" }, "product" : "Comfi Bunk Bed", "seller" : { "name" : "Joe Furniture" } } { "_id" : { "$oid" : "5699ac424f6d3348ac3ef60f" }, "product" : "Bed Side Table", "seller" : { "name" : "Joe Furniture" } } { "_id" : { "$oid" : "5699ac424f6d3348ac3ef610" }, "product" : "Study Table", "seller" : { "name" : "Joe Furniture" } } { "_id" : { "$oid" : "5699ac424f6d3348ac3ef612" }, "product" : "Study Table", "seller" : { "name" : "Sam Furniture" } } { "_id" : { "$oid" : "5699ac424f6d3348ac3ef613" }, "product" : "Study Table", "seller" : { "name" : "Sam Furniture" } } { "_id" : { "$oid" : "5699ac424f6d3348ac3ef614" }, "product" : "Wooden Chair", "seller" : { "name" : "Sam Furniture" } } Jan 16, 2016 2:19:01 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Closed connection [connectionId{localValue:2, serverValue:126}] to 127.0.0.1:27017 because the pool has been closed.
Download the source code
This was an example about MongoDB, querying documents.