Java MongoDB : Query document
In this tutorial, we show you few common ways to get or query document from collection.
Test Data
Insert 5 dummy documents for testing.
{ "_id" : { "$oid" : "id"} , "number" : 1 , "name" : "mkyong-1"}
{ "_id" : { "$oid" : "id"} , "number" : 2 , "name" : "mkyong-2"}
{ "_id" : { "$oid" : "id"} , "number" : 3 , "name" : "mkyong-3"}
{ "_id" : { "$oid" : "id"} , "number" : 4 , "name" : "mkyong-4"}
{ "_id" : { "$oid" : "id"} , "number" : 5 , "name" : "mkyong-5"}
1. Find() examples
1.1 Get first matched document only.
DBObject doc = collection.findOne();
System.out.println(dbObject);
Output
{ "_id" : { "$oid" : "id"} , "number" : 1 , "name" : "mkyong-1"}
1.2 Get all matched documents.
DBCursor cursor = collection.find();
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
Output
{ "_id" : { "$oid" : "id"} , "number" : 1 , "name" : "mkyong-1"}
{ "_id" : { "$oid" : "id"} , "number" : 2 , "name" : "mkyong-2"}
{ "_id" : { "$oid" : "id"} , "number" : 3 , "name" : "mkyong-3"}
{ "_id" : { "$oid" : "id"} , "number" : 4 , "name" : "mkyong-4"}
{ "_id" : { "$oid" : "id"} , "number" : 5 , "name" : "mkyong-5"}
1.3 Get single field from matched document.
BasicDBObject allQuery = new BasicDBObject();
BasicDBObject fields = new BasicDBObject();
fields.put("name", 1);
DBCursor cursor = collection.find(allQuery, fields);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
Output
{ "_id" : { "$oid" : "id"} , "name" : "mkyong-1"}
{ "_id" : { "$oid" : "id"} , "name" : "mkyong-2"}
{ "_id" : { "$oid" : "id"} , "name" : "mkyong-3"}
{ "_id" : { "$oid" : "id"} , "name" : "mkyong-4"}
{ "_id" : { "$oid" : "id"} , "name" : "mkyong-5"}
2. Find() and Comparison
2.1 Get all documents where number = 5
.
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("number", 5);
DBCursor cursor = collection.find(whereQuery);
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
Output
{ "_id" : { "$oid" : "id"} , "number" : 5 , "name" : "mkyong-5"}
2.2 $in
example – Get documents where number in 2, 4 and 5
.
BasicDBObject inQuery = new BasicDBObject();
List<Integer> list = new ArrayList<Integer>();
list.add(2);
list.add(4);
list.add(5);
inQuery.put("number", new BasicDBObject("$in", list));
DBCursor cursor = collection.find(inQuery);
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
Output
{ "_id" : { "$oid" : "id"} , "number" : 2 , "name" : "mkyong-2"}
{ "_id" : { "$oid" : "id"} , "number" : 4 , "name" : "mkyong-4"}
{ "_id" : { "$oid" : "id"} , "number" : 5 , "name" : "mkyong-5"}
2.3 $gt $lt
example – Get documents where 5 > number > 2
.
BasicDBObject gtQuery = new BasicDBObject();
gtQuery.put("number", new BasicDBObject("$gt", 2).append("$lt", 5));
DBCursor cursor = collection.find(gtQuery);
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
Output
{ "_id" : { "$oid" : "id"} , "number" : 3 , "name" : "mkyong-3"}
{ "_id" : { "$oid" : "id"} , "number" : 4 , "name" : "mkyong-4"}
2.4 $ne
example – Get documents where number != 4
.
BasicDBObject neQuery = new BasicDBObject();
neQuery.put("number", new BasicDBObject("$ne", 4));
DBCursor cursor = collection.find(neQuery);
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
Output
{ "_id" : { "$oid" : "id"} , "number" : 1 , "name" : "mkyong-1"}
{ "_id" : { "$oid" : "id"} , "number" : 2 , "name" : "mkyong-2"}
{ "_id" : { "$oid" : "id"} , "number" : 3 , "name" : "mkyong-3"}
{ "_id" : { "$oid" : "id"} , "number" : 5 , "name" : "mkyong-5"}
3. find() and Logical
3.1 $and
example – get documents where number = 2 and name = 'mkyong-2'
.
BasicDBObject andQuery = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
obj.add(new BasicDBObject("number", 2));
obj.add(new BasicDBObject("name", "mkyong-2"));
andQuery.put("$and", obj);
System.out.println(andQuery.toString());
DBCursor cursor = collection.find(andQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
Output
{ "$and" : [ { "number" : 2} , { "name" : "mkyong-2"}]}
{ "_id" : { "$oid" : "id"} , "number" : 2 , "name" : "mkyong-2"}
4. find() and Regex
Find document with regular expression pattern.
4.1 $regex
example – get documents where name like pattern 'Mky.*-[1-3]', case insensitive
.
BasicDBObject regexQuery = new BasicDBObject();
regexQuery.put("name",
new BasicDBObject("$regex", "Mky.*-[1-3]")
.append("$options", "i"));
System.out.println(regexQuery.toString());
DBCursor cursor = collection.find(regexQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
Output
{ "name" : { "$regex" : "Mky.*-[1-3]" , "$options" : "i"}}
{ "_id" : { "$oid" : "515ad59e3004c89329c7b259"} , "number" : 1 , "name" : "mkyong-1"}
{ "_id" : { "$oid" : "515ad59e3004c89329c7b25a"} , "number" : 2 , "name" : "mkyong-2"}
{ "_id" : { "$oid" : "515ad59e3004c89329c7b25b"} , "number" : 3 , "name" : "mkyong-3"}
There are more…
Read this MongoDB operator documentation for complete set of query operators supported in MongoDB.
Read this MongoDB operator documentation for complete set of query operators supported in MongoDB.
5. Full Example
package com.mkyong.core;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
/**
* Java MongoDB : Query document
*
* @author mkyong
*
*/
public class QueryApp {
public static void insertDummyDocuments(DBCollection collection) {
List<DBObject> list = new ArrayList<DBObject>();
Calendar cal = Calendar.getInstance();
for (int i = 1; i <= 5; i++) {
BasicDBObject data = new BasicDBObject();
data.append("number", i);
data.append("name", "mkyong-" + i);
// data.append("date", cal.getTime());
// +1 day
cal.add(Calendar.DATE, 1);
list.add(data);
}
collection.insert(list);
}
public static void main(String[] args) {
try {
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("yourdb");
// get a single collection
DBCollection collection = db.getCollection("dummyColl");
insertDummyDocuments(collection);
System.out.println("1. Find first matched document");
DBObject dbObject = collection.findOne();
System.out.println(dbObject);
System.out.println("\n1. Find all matched documents");
DBCursor cursor = collection.find();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
System.out.println("\n1. Get 'name' field only");
BasicDBObject allQuery = new BasicDBObject();
BasicDBObject fields = new BasicDBObject();
fields.put("name", 1);
DBCursor cursor2 = collection.find(allQuery, fields);
while (cursor2.hasNext()) {
System.out.println(cursor2.next());
}
System.out.println("\n2. Find where number = 5");
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("number", 5);
DBCursor cursor3 = collection.find(whereQuery);
while (cursor3.hasNext()) {
System.out.println(cursor3.next());
}
System.out.println("\n2. Find where number in 2,4 and 5");
BasicDBObject inQuery = new BasicDBObject();
List<Integer> list = new ArrayList<Integer>();
list.add(2);
list.add(4);
list.add(5);
inQuery.put("number", new BasicDBObject("$in", list));
DBCursor cursor4 = collection.find(inQuery);
while (cursor4.hasNext()) {
System.out.println(cursor4.next());
}
System.out.println("\n2. Find where 5 > number > 2");
BasicDBObject gtQuery = new BasicDBObject();
gtQuery.put("number", new BasicDBObject("$gt", 2).append("$lt", 5));
DBCursor cursor5 = collection.find(gtQuery);
while (cursor5.hasNext()) {
System.out.println(cursor5.next());
}
System.out.println("\n2. Find where number != 4");
BasicDBObject neQuery = new BasicDBObject();
neQuery.put("number", new BasicDBObject("$ne", 4));
DBCursor cursor6 = collection.find(neQuery);
while (cursor6.hasNext()) {
System.out.println(cursor6.next());
}
System.out.println("\n3. Find when number = 2 and name = 'mkyong-2' example");
BasicDBObject andQuery = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
obj.add(new BasicDBObject("number", 2));
obj.add(new BasicDBObject("name", "mkyong-2"));
andQuery.put("$and", obj);
System.out.println(andQuery.toString());
DBCursor cursor7 = collection.find(andQuery);
while (cursor7.hasNext()) {
System.out.println(cursor7.next());
}
System.out.println("\n4. Find where name = 'Mky.*-[1-3]', case sensitive example");
BasicDBObject regexQuery = new BasicDBObject();
regexQuery.put("name",
new BasicDBObject("$regex", "Mky.*-[1-3]")
.append("$options", "i"));
System.out.println(regexQuery.toString());
DBCursor cursor8 = collection.find(regexQuery);
while (cursor8.hasNext()) {
System.out.println(cursor8.next());
}
collection.drop();
System.out.println("Done");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}
Done.
very Useful.. Thank you the article.
I am new to mongo db. I am learning newly. Your articles are very very resourceful. I want to retrieve the data alone from the db. Example :
number:1 name: mkyong-1
number: 2 name: mkyong-2
number:3 name: mkyong-3
number: 5 name: mkyong-5
instead of :
{ “_id” : { “$oid” : “id”} , “number” : 1 , “name” : “mkyong-1”}
{ “_id” : { “$oid” : “id”} , “number” : 2 , “name” : “mkyong-2”}
{ “_id” : { “$oid” : “id”} , “number” : 3 , “name” : “mkyong-3”}
{ “_id” : { “$oid” : “id”} , “number” : 5 , “name” : “mkyong-5”}
Can you say me how could i do it? I need it to do in my project . Thank u in advance.
Hi ,
I have question regarding mongo clustering
How to connect if mongo have multiple ip and how to determine which one is primary ip to insert and update value
Is there any way to iterate over database and delete some unused collection of choice or iterating over a array containing collection names and dropping them one by one.
How do include the user id and password?
Hi,
can you please post on how $where can be used in BasicDBobject
or may be usage of $function
What is the main job of BasicDBObject ??
hi its great work How can find the document in MongoDB http://programmershelper.com/mongodb-select-query/
Is it possible to query in mongodb using regular expressions. but, those regular expressions should work on the key field rather than the value field: example: Board Collection: “id” :objectId(“57d5dsg55sad”), “pin0”:{} , “pin1”:{}, “pin2”:{}. now is it possible to query the keys pin0,pin1 using some sort of regular expression? ex. “$regex,pin.*-[1-100]”. (I’d like to retrieve all the pins but it’s either done in a for loop which I wouldn’t prefer or just use regular expressions in the query.put example. query.put(“$regex,pin.*-[1-100]”, “red” )
I am having a doubt in my code. Every one has tried using this. basicobj.put(“name”,”autobots”).
and then colc.insert(basicobj). But i wanna do like this.
basicobj.put(“1”,obj);
where obj is my class obj and i wanna insert it . could u help me
hello;
if i need to select aquery just like field1=”sth1″ and field2=”sth2″
where its retreive one document only without using DBCurser
how i could do that ?
please help me 🙂
Can we find all the fields of all the documents in a collection along with their datatypes……….
hi Mkyong, i want to find count of embedding documents. Anyone please help me.
I have a db that list objects with ids, however I want to fetch a field named lets say a url but I want to get all the urls and also not just any url I want to get the ones that include some partial text and filter using that text and and give me all of those urls. I can’t seem to get it to do that.
eg:
DB db= mongo.getDB(thedatabase);
DBCollection coll= db.getCollection(thecollection);
whereQuery.put(“Url”, “http://www.bhjbdvuis”);
DBCursor cursor= coll.find(whereQuery);
while (cursor.hasNext())
{
System.out.println(cursor.next());
}
sorry forgot a piece of the code
DB db= mongo.getDB(thedatabase);
DBCollection coll= db.getCollection(thecollection);
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put(“Url”, “http://www.bhjbdvuis”);
DBCursor cursor= coll.find(whereQuery);
while (cursor.hasNext())
{
System.out.println(cursor.next());
}
This returns all the items in the DB
Is nested Or possible like below? please let me know.thank you!
db.collectiontest.find( {$and:[ {body:/test/} , {$or:[{ body: /gujarat/ }, {url: /gujarat/ } ]} ]} ,{ _id:0 }).count()
Thank you for this useful blog, Mkyong! Any example of using Java Date or Datetime for $lte, $gt types of query?
Hi, Mkyong! I like your website!
Thank you a lot!!
I have problem! Please help me!
I have code below:
queryTitle=new BasicDBObject(“title”, new BasicDBObject(“$regex”, keySearch));
DBCursor dbcur=db.getCollection(“Colection”).find(queryTitle)
The dbcur return so much DBObject. How i can get DBObject like “lazy loading”.
If i have a button, when i clicked, dbcur get 10 value, next click it get next 10 value.
Thank!
Thanks … Great Tutorial ..
Hi! Thank you for great tutorials 🙂
But what i cant seem to figure out is how to search for a text String through all the keys.
I have a Grid FSfile:
{ “_id” : { “$oid” : “5174f41f300452a80bf45d4c”} , “chunkSize” : 262144 , “length” : 104873 , “md5” : “337875b0e3e2debb2367838e9f097ef1” , “filename” : “test.zip” , “contentType” : null , “uploadDate” : { “$date” : “2013-04-22T08:26:07.749Z”} , “aliases” : null ,
“metadata” : { “filename” : “test” , : “from” : “Iceland” , “to” : “Nederland” , “tags” : [ “tag1, tag2, tag3”] , “createdDate” : { “$date” : “2013-04-22T08:26:07.785Z”}}}
I want to be able to search for example for ” land” through all the metadata keys. I have only figured out how to search for one
query.put(“metadata.from”, new BasicDBObject(“$regex”, pattern).append(“$options”, “i”));
GREAT, I’ve read the mongo docs. Printing out the contents of a cursor list is easy. However, what no one seems to want to post about is returning cursor lists and serializing them as json.
from the docs:
OK great, but my method fails when I return obj as a list or try to serialize that as json for a response.
Loop the cursor, and play around the value and put it back to list.
I made a simple utility function to do this, (Serialize results from a cursor into JSON) I hope it’s of some use to you
If i want a single field from a record, how do i do that?
Select single field “name”, see article above
what should I do?i only want to display name but it also prints id also
I’m using mongojava driver 3.0.2.If I have to get database then I have to write getDataBase() instead of getDB().Problem is I want to select “name” column value .
Above code gives me error to split it in declaration.I have tried this code but doesn’t show output and no error too.
FindIterable iterable = db.getCollection(“Restaurant”).find();
iterable.forEach(new Block() {
public void apply(final Document document) {
System.out.println(“OUTPUT IS ” +document);
}
});
This might be late for you, but I found this link useful : http://stackoverflow.com/questions/9639260/query-fields-in-a-mongodb-collection