DevilCode
DevilCode

Reputation: 1100

Get last inserted document with tag MongoDB Java

I am working in Java using the 2.6 Java driver.

I am using the "i" tag to identify the site.

What is the best way to query in order to get the last inserted document with "i" = "99159" ?

Please provide some example code.

An example document in mongo:

 {
   "_id": ObjectId("560bc0eee4b01a37814ee444"),
   "dataDate": "2015-09-30T11:00:00Z",
   "i": "99159",
   "lat": "50.61359",
   "lon": "-1.95875",
   "name": "SWANAGE",
   "country": "ENGLAND",
   "continent": "EUROPE",
   "elevation": "10.0",
   "Period": {
     "type": "Day",
     "value": "2015-09-30Z",
     "Rep": {
       "H": "75.9",
       "T": "14.7",
       "Dp": "10.5",
       "MinSinceMidnight": "600"
    }
  }
}   

Upvotes: 0

Views: 1957

Answers (1)

Dev
Dev

Reputation: 13753

As you have _id as ObjectId, so you can sort your data on _id to get last inserted record.

Sample code:

 MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017));
 MongoClient mongo = new MongoClient("localhost", 27017);
 DB mongodb = (DB) mongo.getDB("testDB");
 DBCollection collection = mongodb.getCollection("collection");

 BasicDBObject findObject = new BasicDBObject().append("i","99159");
 BasicDBObject sortObject = new BasicDBObject().append("_id", -1);

 DBCursor cur = collection.find(findObject).sort(sortObject).limit(1);
 DBObject obj = cur.one();

Upvotes: 5

Related Questions