当前位置:网站首页>MongonDB API使用
MongonDB API使用
2022-07-26 05:18:00 【北海怪兽Monster】
mongodb-driver是mongo官方推出的java连接mongoDB的驱动包,相当于JDBC驱动。我们现在来使用mongodb-driver完成对Mongodb的操作。
添加依赖,注意自己使用得版本
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb‐driver</artifactId>
<version>3.10.1</version>
</dependency>
测试代码
public class MongoTest {
// 客户端
private MongoClient mongoClient;
// 集合
private MongoCollection<Document> comment;
@Before
public void init() {
//1. 创建操作MongoDB的客户端
mongoClient = new MongoClient("192.168.200.128");
// MongoClient mongoClient = new MongoClient("192.168.200.128",27017);
//2. 选择数据库 use commentdb
MongoDatabase commentdb = mongoClient.getDatabase("commentdb");
//3. 获取集合 db.comment
comment = commentdb.getCollection("comment");
}
//查询所有数据db.comment.find()
@Test
public void test1() {
//4. 使用集合进行查询,查询所有数据db.comment.find()
FindIterable<Document> documents = comment.find();
//5. 解析结果集(打印)
// "_id" : "1", "content" : "到底为啥出错", "userid" : "1012", "thumbup" : 2020 }
for (Document document : documents) {
System.out.println("------------------------------");
System.out.println("_id:" + document.get("_id"));
System.out.println("content:" + document.get("content"));
System.out.println("userid:" + document.get("userid"));
System.out.println("thumbup:" + document.get("thumbup"));
}
}
@After
public void after() {
// 释放资源,关闭客户端
mongoClient.close();
}
// 根据条件_id查询数据,db.comment.find({"_id" : "1"})
@Test
public void test2() {
// 封装查询条件 ,可以传一个Map集合,进行多条件查询
BasicDBObject bson = new BasicDBObject("_id", "1");
// 执行查询
FindIterable<Document> documents = comment.find(bson);
for (Document document : documents) {
System.out.println("------------------------------");
System.out.println("_id:" + document.get("_id"));
System.out.println("content:" + document.get("content"));
System.out.println("userid:" + document.get("userid"));
System.out.println("thumbup:" + document.get("thumbup"));
}
}
// 新增db.comment.insert({"_id" : "5", "content" : "坚持就是胜利123", "userid" : "1018", "thumbup" : 1212})
@Test
public void test3() {
// 封装新增数据
Map<String, Object> map = new HashMap<>();
map.put("_id", "6");
map.put("content", "新增测试");
map.put("userid", "1019");
map.put("thumbup", "666");
// 封装新增文档对象
Document document = new Document(map);
// 执行新增 新增多条:insertMany(List<Document>)
comment.insertOne(document);
}
// 修改,db.comment.update({"_id" : "5"},{$set:{"userid" : "888"}})
@Test
public void test4() {
//创建修改的条件
BasicDBObject filter = new BasicDBObject("_id", "6");
//创建修改的值
BasicDBObject update = new BasicDBObject("$set", new Document("userid", "999"));
// 执行修改
comment.updateOne(filter, update);
}
// 删除,db.comment.remove({"_id" : "5"})
@Test
public void test5() {
// 创建删除的条件
BasicDBObject bson = new BasicDBObject("_id", "6");
// 执行删除
comment.deleteOne(bson);
}
}
Boot 使用
yml 配置
SpringData 查询
持久层编写,只需要集成指定接口,框架就会扫描到。
而且而且!!!!!!!!!!!!
SpringDataMongoDB,支持通过查询方法名进行查询定义的方式
你只需要按照规定,指定方法名字!!!框架帮你生成 MongoDB 查询语句!
但是一定要继承这个类(只针对查询语句!!!!!),并且springData框架还封装了一些方法,可以直接使用!
import org.springframework.data.mongodb.repository.MongoRepository;
public interface CommentRepository extends MongoRepository<Comment, String> {
//SpringDataMongoDB,支持通过查询方法名进行查询定义的方式
//根据文章id查询文章评论数据
List<Comment> findByArticleid(String articleId);
//根据发布时间和点赞数查询查询
// List<Comment> findByPublishdateAndThumbup(Date date, Integer thumbup);
//根据用户id查询,并且根据发布时间倒序排序
// List<Comment> findByUseridOrderbOrderByPublishdateDesc(String userid);
}
MongoRepository 这和接口默认提供了一些方法,便捷使用
模板类使用
private MongoTemplate mongoTemplate;
上面得查询使用得是SpringData提供得。
针对一些修改操作,还是只有通过模板类进行使用。
解决重复点赞问题
将 用户id和文章id 作为key ,存放到redis中,因为经常读写,所以redis性能更高!
在每次进行点赞操作之前进行判断即可。
在加载时,也可以将对应点赞信息加载出来,在前端给用户设置 点赞按钮不可用
边栏推荐
- TZC 1283: simple sorting - function method
- FPGA question brushing sequence detection
- [pytorch] install torch 1.8.1 and check whether torch version and GPU are available
- Attack and defense world flatscience
- Okaleido launched the fusion mining mode, which is the only way for Oka to verify the current output
- Full analysis of domain name resolution process means better text understanding
- Shell流程控制(重点)、if 判断、case 语句、let用法、for 循环中有for (( 初始值;循环控制条件;变量变化 ))和for 变量 in 值 1 值 2 值 3… 、while 循环
- 安装NCCL\mpirun\horovod\nvidia-tensorflow(3090Ti)
- 35. Search the insertion position
- TZC 1283: simple sort - select sort
猜你喜欢

Security permission management details

Nacos registry

Embedded sharing collection 21

YOLOV3预备工作

OD-Paper【2】:Fast R-CNN

Getaverse, a distant bridge to Web3

Okaleido上线聚变Mining模式,OKA通证当下产出的唯一方式

If MySQL calculates the current month change / current month increase / year-on-year change / year-on-year increase?
C语言详解系列——函数的认识(3)形参,实参,嵌套调用和链式访问

Earth system model (cesm) practical technology
随机推荐
Excel VBA: summarize calculation output results by date (SUMIF)
MODFLOW flex, GMS, FEFLOW, hydraus practical application
ThreadLocal transfer between parent and child threads in asynchronous
C语言实现发牌功能基本方法
Shell process control (emphasis), if judgment, case statement, let usage, for ((initial value; loop control condition; variable change)) and for variable in value 1 value 2 value 3..., while loop
Earth system model (cesm) practical technology
flex布局原理及常见的父项元素
NPM operation instruction
no networks found in /etc/cni/net.d
10. 正则表达式匹配
Map making of environmental impact assessment based on remote sensing interpretation and GIS technology
Nacos introduction and deployment
Real scientific weight loss
Shell的read 读取控制台输入、read的使用
Reason for pilot importerror: cannot import name 'pilot_ Version 'from' PIL ', how to install pilot < 7.0.0
Use playbook in ansible
Excel vba: saving multiple worksheets as new files
Use flutter to adjust a color filter for the picture of my little sister
怎么办理聚合收款码
Chinese character style transfer --- learn the conversion and generation of one to many programmed Chinese characters through generation confrontation network