1、查询指定字段
collection.find().projection(fields(include("username","pwd"),excludeId()));//返回username与pwd字段且不返回_id字段
Document doc = new Document().append("_id", 0).append("username",1).append("pwd",1);//指定查询字段,0为不包含此字段,1为包含此字段
FindIterable<Document> findIterable = collection.find().projection(doc);
两种方法查询结果相同,区别是第一种方法使用了include等函数,需要包含头文件 import static com.mongodb.client.model.Projections.*;
第二种方法使用Document代替了include等函数,无需包含此头文件。
2、按条件查询
Document myDoc = collection.find(and(eq("username","liuchao"),eq("pwd","12345"))).first();
//此方法需包含头文件import static com.mongodb.client.model.Filters.*;
Document myDoc = collection.find(new Document("username", "liuchao").append("pwd", "12345")).first();
//无需包含上面的头文件
3、对查询结果排序
FindIterable<Document> iterable = collection.find().sort(ascending("title"));//按title升序排列
FindIterable<Document> iterable = collection.find().sort(ascending("title","words"));//按title和words升序排列
FindIterable<Document> iterable = collection.find().sort(descending("title"));//按title降序排列
FindIterable<Document> iterable = collection.find().sort(new Document("time",-1));//按time降序排列
4、获取满足条件的前n条数据
MongoCursor<Document> cursor = collection.find(new Document("username","liuchao")).sort(new Document("time",-1)).limit(n).iterator();
//对满足条件username=“liuchao”的结果进行降序排列,并获取前n条数据。(n=0获取全部)
collection.find().projection(fields(include("username","pwd"),excludeId()));//返回username与pwd字段且不返回_id字段
Document doc = new Document().append("_id", 0).append("username",1).append("pwd",1);//指定查询字段,0为不包含此字段,1为包含此字段
FindIterable<Document> findIterable = collection.find().projection(doc);
两种方法查询结果相同,区别是第一种方法使用了include等函数,需要包含头文件 import static com.mongodb.client.model.Projections.*;
第二种方法使用Document代替了include等函数,无需包含此头文件。
2、按条件查询
Document myDoc = collection.find(and(eq("username","liuchao"),eq("pwd","12345"))).first();
//此方法需包含头文件import static com.mongodb.client.model.Filters.*;
Document myDoc = collection.find(new Document("username", "liuchao").append("pwd", "12345")).first();
//无需包含上面的头文件
3、对查询结果排序
FindIterable<Document> iterable = collection.find().sort(ascending("title"));//按title升序排列
FindIterable<Document> iterable = collection.find().sort(ascending("title","words"));//按title和words升序排列
FindIterable<Document> iterable = collection.find().sort(descending("title"));//按title降序排列
FindIterable<Document> iterable = collection.find().sort(new Document("time",-1));//按time降序排列
4、获取满足条件的前n条数据
MongoCursor<Document> cursor = collection.find(new Document("username","liuchao")).sort(new Document("time",-1)).limit(n).iterator();
//对满足条件username=“liuchao”的结果进行降序排列,并获取前n条数据。(n=0获取全部)