Neo-coder
Neo-coder

Reputation: 7840

Converting Mongodb query in java

Hi my mongo collection having following documents

{ 
      "_id" : ObjectId("523db8f324c8fa2acac03703"), 
      "name" : "abc",
      "timestamp" : 1379776720000
}
{ 
      "_id" : ObjectId("523db8f324c8fa2acac03704"), 
      "name" : "abc",
      "timestamp" : 1379776730000
}
{ 
      "_id" : ObjectId("523db8f324c8fa2acac03705"), 
      "name" : "abc1",
      "timestamp" : 1379776800000
}

And I was write mongo query for finding largest timestamp of given name as below

db.collections_name.find({"name":"abc"}).sort({"timestamp":-1}).limit(1)

It work fine on mongo shell but I want to implement this query in Java code, How I write same query in Java.

Upvotes: 0

Views: 433

Answers (1)

Ori Dar
Ori Dar

Reputation: 19000

MongoClient mc = new MongoClient();
DB db = mc.getDB("...");
DBCollection collection = db.getCollection("...");
DBCursor c = collection.find(new BasicDBObject("name","abc")).sort(new BasicDBObject("timestamp",-1)).limit(1);

Don't forget to put your db and collection name

Upvotes: 3

Related Questions