Java操作MongoDB常用API文档

本文介绍了MongoDB中多种实用的查询技巧,包括指定字段查询、条件查询、结果排序及获取前n条数据的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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获取全部)



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值