我使用2.6 Java驱动程序在Java中工作。
我使用“i”标签来识别网站。
查询以获取带有“i”=“99159”的最后一个插入文档的最佳方法是什么?
请提供一些示例代码。
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"
}
}
}
答案 0 :(得分:5)
由于_id
为ObjectId
,因此您可以在_id
上对数据进行排序,以获取最后插入的记录。
示例代码:
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();