因为需要最近使用了mongoDB,上官网一看现在都mongo-java-driver-3.2.2.jar了(以前接触2.X).
于是下载了最新版驱动来用(DB版本:db version v2.4.9),因为新,资料少所以也遇到一些问题,以下就分享出来:
1.官方文档里面的东西已经很全面了.常操作一看就明白,就不多说了,可通过以下链接自行查看
https://docs.mongodb.org/getting-started/java/query/
2.如果查询指定列应该怎么写呢?X度了一大圈大都是2.几的写法,无奈只能慢慢查API了
参考:http://api.mongodb.org/java/current/com/mongodb/client/FindIterable.html
projection(Bson projection)
Sets a document describing the fields to return for all matching documents.
完整的方法:
//读取出来保存到别一个集合
MongoClient mongoClient = new MongoClient( "localhost" ,27017 );
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document> collection = database.getCollection("geoptima");
Document temp = new Document();
temp.put("_id",0);
temp.put("geoptima.subscriber",1);
System.out.println( temp.toJson() );
//查询指定列的数据 projection
FindIterable<Document> docs = collection.find(
).sort(new Document("geoptima.subscriber.start",-1) ).projection(temp).limit(5);
MongoCursor<Document> cursor = docs.iterator();
int i =1;
while(cursor.hasNext()){
Document doc = cursor.next();
System.out.println(i++ +" : "+doc.toJson());
}
mongoClient.close();
注:
temp.put("_id",0): 等于0表示些列不显示
sort项里面的值为-1时:表示降序.>=0时为升序.
对mongodb接触不多,大家有更好的方法请分享一下哦!
最近不知怎么的访问CSDN好慢呢...