tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 No SQL > Mongo DB > How to get first document from Collection

How to get first document from Collection 

MongoDB is a scalable, high-performance, open source NoSQL database. It offers Ad hoc queries, Indexing, Replication, Load balancing, File storage (GridFS), Aggregation, MapReduce and Server-side JavaScript execution. This requires the library mongo-2.8.0.jar to be present in the classpath. The following example shows how to get the first document from collection matching the query.

File Name  :  
Author  :  Sudhakar KV
Email  :  [email protected]
package com.bethecoder.tutorials.mongodb.tests;


import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class FindOneTest {

   @param args
  public static void main(String[] args) {

    try {
      //Connect to mongoDB with given IP and PORT
      Mongo mongo = new Mongo("localhost"27017);
      //Get the database object
      DB database = mongo.getDB("mytestdb");
      //Gets a collection with a given name.
      DBCollection collection = database.getCollection("mynums");
      //Query and get the first object from this collection matching the query
      DBObject query = new BasicDBObject().append("even"true);
      DBObject firstEven = collection.findOne(query);
    catch (UnknownHostException e) {
    catch (MongoException e) {

It gives the following output,
{ "_id" : 2 , "num" : 2 , "even" : true , "num^2" : 4.0}



Books Recommendation

bl  br