How to Retrieve MongoDB Document in Eclipse IDE Using Java

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

This tutorial will show users how to create a query for retrieving MongoDB documents in Eclipse using Java. Before beginning, the MongoDB and a compatible version of the MongoDB Java driver must be properly installed and configured. The latest versions of both Java JDK and Eclipse IDE should be used to achieve the best result.

Prerequisites

  • The MongoDB and compatible MongoDB Java driver must be properly installed and configured before beginning.

  • Confirm the latest versions of Java JDK and Eclipse IDE are properly installed and configured before beginning.

  • Confirm the MongoDB service is running.

NOTE: The examples in this tutorial use MongoDB version 4.0 and MongoDB Java Driver 3.8.2.

The MongoDB Test Data

  • Insert the dummy documents into the preferred collection. In this example the collection will be named “playerInfo”
IDNumberPlayer NameNationality
5cd56e315623d0556fb0b45e1JonathanFilipino
5cd64bc45623d00955cb3cbf2DipSeaGerman
5cd64c5b5623d009c1fff26d3SpanionFilipino
5cd671a05623d014e610973c4MoreDanMexican
5cd671ca5623d0150e44c7c25RyteckJapanese

How to Query MongoDB Document using find() and Regex Method

  • This section will demonstrate how to find a document using a regular expression pattern.
1
2
3
MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017"); // (1)
MongoDatabase db = mongo.getDatabase("PlayerDB"); // (2)
MongoCollection<document> playerColl = db.getCollection("playerInfo"); // (3)
  • The above code establishes a connection to the MongoDB deployment and accesses both the database (PlayerDB) and the specified collection (playerInfo).
1
2
3
4
5
6
7
8
9
10
BasicDBObject regexQuery = new BasicDBObject();
regexQuery.put("playerName", new BasicDBObject("$regex", "sp").append("$options", "i")); // (4)


FindIterable<document> cursor = playerColl.find(regexQuery); // (5)
MongoCursor<document> iterator = cursor.iterator(); // (6)
while (iterator.hasNext()) {
iterator.next();
}
cursor.forEach((Block<document>) System.out::println); // (7)
  1. BasicDBObject is like a “Map<?,?>” that stores data in a key-value pair. The "$options","i" instructs the query the search will not be be case sensitive so it will match data in both upper and lower case.

  2. FindIterable allows the user to iterate through the find() result.

  3. Executes looping through the documents and printing the documents out in the console.
  • The results should resemble something like the following:
1
Document{{_id=5cd56e315623d0556fb0b45e, player-name=Jonathan, number=1, nationality=Filipino}}

How to Retrieve Only the First Matched MongoDB Document using Java

  • The command in the flowing example shows how to retrieve only the first document within the MongoDB collection:
1
2
3
4
5
MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017");
MongoDatabase db = mongo.getDatabase("PlayerDB");
MongoCollection<document> playerColl = db.getCollection("playerInfo");

system.out.println(playerColl.find().first());
  • The first() method limits the query to retrieve only the first document in the collection.
  • The results should resemble something like this:
1
Document{{_id=5cd64c5b5623d009c1fff26d, player-name=Spanion, number=3, nationality=Filipino}}

How to Retrieve All MongoDB Document using Java

  • The command in the flowing example shows how to retrieve all of the documents within the MongoDB collection:
1
2
3
4
5
6
7
8
9
MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017");
MongoDatabase db = mongo.getDatabase("PlayerDB");
MongoCollection<document> playerColl = db.getCollection("playerInfo");

palyerColl.find();

while(cursor.hasNext()) {
System.out.println(cursor.next());
}
  • The find() method will essentially locate all documents within the MongoDB Collection.
  • The results should display all the MongoDB documents within the MongoDB collection, that should resemble the following:
1
2
3
4
5
Document{{_id=5cd56e315623d0556fb0b45e, player-name=Jonathan, number=1, nationality=Filipino}}
Document{{_id=5cd64bc45623d00955cb3cbf, player-name=Dipsea, number=2, nationality=German}}
Document{{_id=5cd64c5b5623d009c1fff26d, player-name=Spanion, number=3, nationality=Filipino}}
Document{{_id=5cd671a05623d014e610973c, player-name=MoreDan, number=4, nationality=Mexican}}
Document{{_id=5cd671ca5623d0150e44c7c2, player-name=Ryteck, number=5, Nationality=Japanese}}

How to Find and Compare a MongoDB Document using Java.

  • The code in the below example will return all documents with the value of the field “nationality” being “Filipino”.
1
2
3
4
5
6
7
8
9
10
11
12
MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017");
MongoDatabase db = mongo.getDatabase("PlayerDB");
MongoCollection<document> playerColl = db.getCollection("playerInfo");

BasicDBObject whereQuery = new BasicDBObject();
compareQuery.put("nationality", "Filipino");

FindIterable<document> cursor = playerColl.find(compareQuery);
MongoCursor<document> iterator = cursor.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
  • The find() method reads the compareQuery as a filter to query the documents within the MongoDB collection.

  • The results should return something that resembles the following:

1
2
Document{{_id=5cd56e315623d0556fb0b45e, player-name=Jonathan, number=1, nationality=Filipino}}
Document{{_id=5cd64c5b5623d009c1fff26d, player-name=Spanion, number=3, nationality=Filipino}}

How to Find a MongoDB Document Using “$ne” in Java.

  • Note, the $ne operator in the find() method will not display all the MongoDB documents that match the specified criteria.
1
2
3
4
5
6
7
8
9
10
11
12
MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017");
MongoDatabase db = mongo.getDatabase("PlayerDB");
MongoCollection<document> playerColl = db.getCollection("playerInfo");

BasicDBObject neQuery = new BasicDBObject();
neQuery.put("nationality", new BasicDBObject("$ne", "Filipino"));

FindIterable<document> cursor = playerColl.find(neQuery);
MongoCursor<document> iterator = cursor.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
  • The results should return something that resembles the following:
1
2
3
Document{{_id=5cd64bc45623d00955cb3cbf, player-name=Dipsea, number=2, nationality=German}}
Document{{_id=5cd671a05623d014e610973c, player-name=MoreDan, number=4, nationality=Mexican}}
Document{{_id=5cd671ca5623d0150e44c7c2, player-name=Ryteck, number=5, Nationality=Japanese}}

Code Example

  • The preceding codes were written in two Java class. The Main Class MongoClass will call the functions that will perform the queries as explained in the previous section, whereas the MongoFunctionClass holds all the functions shown in the previous section.

The MongoClass code example.

1
2
3
4
5
6
7
8
9
10
11
public class MongoClass {

public static void main(String[] args) {

MongofunctionClass functionCall = new MongofunctionClass();
functionCall.findRegex();
functionCall.findOneDoc();
functionCall.findAndCompare();
functionCall.findNotEqualMe();
}
}
  • The MongofunctionClass test = new MongofunctionClass(); instantiates the MongofunctionClass to access the functionalities.

The MongofunctionClass code example

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
public void findRegex() {
MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017");
MongoDatabase db = mongo.getDatabase("PlayerDB");
MongoCollection<document> colMenu = db.getCollection("playerInfo");

BasicDBObject regexQuery = new BasicDBObject();
regexQuery.put("playerName", new BasicDBObject("$regex", "yes").append("$options", "i"));


FindIterable<document> cursor = playerColl.find(regexQuery);
MongoCursor<document> iterator = cursor.iterator();
while (iterator.hasNext()) {
iterator.next();
}
cursor.forEach((Block<document>) System.out::println);


}



public void findOneDoc() {
MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017");
MongoDatabase db = mongo.getDatabase("PlayerDB");
MongoCollection<document> playerColl = db.getCollection("playerInfo");


System.out.println(playerColl.find().first());
}


public void findAndCompare() {

MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017");
MongoDatabase db = mongo.getDatabase("PlayerDB");
MongoCollection<document> playerColl = db.getCollection("playerInfo");

BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("nationality", "Filipino");

FindIterable<document> cursor = playerColl.find(whereQuery);
MongoCursor<document> iterator = cursor.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
}

public void findNotEqualMe() {
MongoClient mongo = MongoClients.create("mongodb://127.0.0.1:27017");

MongoDatabase db = mongo.getDatabase("PlayerDB");
MongoCollection<document> playerColl = db.getCollection("playerInfo");

BasicDBObject neQuery = new BasicDBObject();
neQuery.put("nationality", new BasicDBObject("$ne", "Filipino"));

FindIterable<document> cursor = playerColl.find(neQuery);
MongoCursor<document> iterator = cursor.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
}

Conclusion

The tutorial explained how to use a basic query for retrieving MongoDB documents in Eclipse using Java with the find() method, namely how to retrieve only the first matched MongoDB document in a collection as well as how to retrieve all of the documents within a MongoDB collection. Bear in mind, the examples in this tutorial used MongoDB version 4.0 and MongoDB Java Driver 3.8.2 for retrieving MongoDB documents in Eclipse using Java.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.