Java操作MongoDB数据库的示例代码
作者:黄河大道东 发布时间:2023-11-23 04:15:51
标签:Java,MongoDB,数据库
目录
环境准备
1.数据库操作
1.1获取所有数据库
1.2获取指定库的所有集合名
1.3.删除数据库
2.文档操作
2.1插入文档
2.2查询文档
2.3分页查询
2.4修改文档
2.5 删除文档
mongodb-driver是mongo官方推出的java连接mongoDB的驱动包,相当于JDBC驱动。
环境准备
step1:创建工程 , 引入依赖
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb‐driver</artifactId>
<version>3.6.3</version>
</dependency>
</dependencies>
step2:创建测试类
import com.mongodb.*;
import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class MogoDBTest {
private static MongoClient mongoClient;
static {
System.out.println("===============MongoDBUtil初始化========================");
mongoClient = new MongoClient("127.0.0.1", 27017);
// 大多使用mongodb都在安全内网下,但如果将mongodb设为安全验证模式,就需要在客户端提供用户名和密码:
// boolean auth = db.authenticate(myUserName, myPassword);
MongoClientOptions.Builder options = new MongoClientOptions.Builder();
options.cursorFinalizerEnabled(true);
// 自动重连true
// options.autoConnectRetry(true);
// the maximum auto connect retry time
// 连接池设置为300个连接,默认为100
// options.maxAutoConnectRetryTime(10);
options.connectionsPerHost(300);
// 连接超时,推荐>3000毫秒
options.connectTimeout(30000);
options.maxWaitTime(5000);
// 套接字超时时间,0无限制
options.socketTimeout(0);
// 线程队列数,如果连接线程排满了队列就会抛出“Out of semaphores to get db”错误。
options.threadsAllowedToBlockForConnectionMultiplier(5000);
options.writeConcern(WriteConcern.SAFE);//
options.build();
}
// =================公用用方法=================
/**
* 获取DB实例 - 指定数据库,若不存在则创建
*/
public static MongoDatabase getDB(String dbName) {
if (dbName != null && !"".equals(dbName)) {
MongoDatabase database = mongoClient.getDatabase(dbName);
return database;
}
return null;
}
/**
* 获取指定数据库下的collection对象
*/
public static MongoCollection<Document> getCollection(String dbName, String collName) {
if (null == collName || "".equals(collName)) {
return null;
}
if (null == dbName || "".equals(dbName)) {
return null;
}
MongoCollection<Document> collection = mongoClient
.getDatabase(dbName)
.getCollection(collName);
return collection;
}
}
1.数据库操作
1.1获取所有数据库
//获取所有数据库
@Test
public void getAllDBNames(){
MongoIterable<String> dbNames = mongoClient.listDatabaseNames();
for (String s : dbNames) {
System.out.println(s);
}
}
1.2获取指定库的所有集合名
//获取指定库的所有集合名
@Test
public void getAllCollections(){
MongoIterable<String> colls = getDB("books").listCollectionNames();
for (String s : colls) {
System.out.println(s);
}
}
1.3.删除数据库
//删除数据库
@Test
public void dropDB(){
//连接到数据库
MongoDatabase mongoDatabase = getDB("test");
mongoDatabase.drop();
}
2.文档操作
2.1插入文档
1.插入单个文档
//插入一个文档
@Test
public void insertOneTest(){
//获取集合
MongoCollection<Document> collection = getCollection("books","book");
//要插入的数据
Document document = new Document("id",1)
.append("name", "哈姆雷特")
.append("price", 67);
//插入一个文档
collection.insertOne(document);
System.out.println(document.get("_id"));
}
2.插入多个文档
//插入多个文档
@Test
public void insertManyTest(){
//获取集合
MongoCollection<Document> collection = getCollection("books","book");
//要插入的数据
List<Document> list = new ArrayList<>();
for(int i = 1; i <= 15; i++) {
Document document = new Document("id",i)
.append("name", "book"+i)
.append("price", 20+i);
list.add(document);
}
//插入多个文档
collection.insertMany(list);
}
2.2查询文档
2.2.1基本查询
1.查询集合所有文档
@Test
public void findAllTest(){
//获取集合
MongoCollection<Document> collection = getCollection("books","book");
//查询集合的所有文档
FindIterable findIterable= collection.find();
MongoCursor cursor = findIterable.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
}
2.条件查询
@Test
public void findConditionTest(){
//获取集合
MongoCollection<Document> collection = getCollection("books","book");
//方法1.构建BasicDBObject 查询条件 id大于2,小于5
BasicDBObject queryCondition=new BasicDBObject();
queryCondition.put("id", new BasicDBObject("$gt", 2));
queryCondition.put("id", new BasicDBObject("$lt", 5));
//查询集合的所有文 通过price升序排序
FindIterable findIterable= collection.find(queryCondition).sort(new BasicDBObject("price",1));
//方法2.通过过滤器Filters,Filters提供了一系列查询条件的静态方法,id大于2小于5,通过id升序排序查询
//Bson filter=Filters.and(Filters.gt("id", 2),Filters.lt("id", 5));
//FindIterable findIterable= collection.find(filter).sort(Sorts.orderBy(Sorts.ascending("id")));
//查询集合的所有文
MongoCursor cursor = findIterable.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
}
2.2.2 投影查询
@Test
public void findAllTest3(){
//获取集合
MongoCollection<Document> collection = getCollection("books","book");
//查询id等于1,2,3,4的文档
Bson fileter=Filters.in("id",1,2,3,4);
//查询集合的所有文档
FindIterable findIterable= collection.find(fileter).projection(new BasicDBObject("id",1).append("name",1).append("_id",0));
MongoCursor cursor = findIterable.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
}
2.3分页查询
2.3.1.统计查询
//集合的文档数统计
@Test
public void getCountTest() {
//获取集合
MongoCollection<Document> collection = getCollection("books","book");
//获取集合的文档数
Bson filter = Filters.gt("price", 30);
int count = (int)collection.count(filter);
System.out.println("价钱大于30的count==:"+count);
}
2.3.2分页列表查询
//分页查询
@Test
public void findByPageTest(){
//获取集合
MongoCollection<Document> collection = getCollection("books","book");
//分页查询 跳过0条,返回前10条
FindIterable findIterable= collection.find().skip(0).limit(10);
MongoCursor cursor = findIterable.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
System.out.println("----------取出查询到的第一个文档-----------------");
//取出查询到的第一个文档
Document document = (Document) findIterable.first();
//打印输出
System.out.println(document);
}
2.4修改文档
//修改文档
@Test
public void updateTest(){
//获取集合
MongoCollection<Document> collection = getCollection("books","book");
//修改id=2的文档 通过过滤器Filters,Filters提供了一系列查询条件的静态方法
Bson filter = Filters.eq("id", 2);
//指定修改的更新文档
Document document = new Document("$set", new Document("price", 44));
//修改单个文档
collection.updateOne(filter, document);
//修改多个文档
// collection.updateMany(filter, document);
//修改全部文档
//collection.updateMany(new BasicDBObject(),document);
}
2.5 删除文档
//删除与筛选器匹配的单个文档
@Test
public void deleteOneTest(){
//获取集合
MongoCollection<Document> collection = getCollection("books","book");
//申明删除条件
Bson filter = Filters.eq("id",3);
//删除与筛选器匹配的单个文档
collection.deleteOne(filter);
//删除与筛选器匹配的所有文档
// collection.deleteMany(filter);
System.out.println("--------删除所有文档----------");
//删除所有文档
// collection.deleteMany(new Document());
}
来源:https://www.cnblogs.com/hhddd-1024/p/14686366.html


猜你喜欢
- 本文介绍了Maven+Tomcat8 实现自动化部署的方法,分享给大家,具体如下:1.配置tomcat-users.xml首先在Tomcat
- ActivityThread功能它管理应用进程的主线程的执行(相当于普通Java程序的main入口函数),并根据AMS的要求(通过IAppl
- SpringBoot版本2.2.4.RELEASE。【1】SpringBoot接收到请求① springboot接收到一个请求返回json格
- 1 二叉排序树的概述本文没有介绍一些基础知识。对于常见查找算法,比如顺序查找、二分查找、插入查找、斐波那契查找还不清楚的,可以看这篇文章:常
- 创建一个用户类类型的集合,手动输入用户库主要是判定输入的用户名和密码是否与库中的匹配做好区别是用户名输入错误还是密码输入错误的提示。定义用户
- using System;using System.Diagnostics;using System.Runtime.InteropServ
- 本文实例为大家分享了C#生成唯一订单号的具体代码,供大家参考,具体内容如下根据GUID+DateTime.Now.Ticks生产唯一订单号/
- 使用 transient 修饰private transient String noColumn;使用 static 修饰private s
- 一、稀疏数组1、什么是稀疏数组当一个数组中大部分元素为0,或者为同一个值的数组时,可以用稀疏数组来保存该数组。稀疏数组,记录一共有几行几列,
- 一、前言虽然jdk1.9版本已经问世,但是许多其他的配套设施并不一定支持jdk1.9版本,所以这里仅带领你配置jdk1.8。而jdk1.9的
- 本文实例分析了Android编程之TextView的字符过滤功能。分享给大家供大家参考,具体如下:TextView可以设置接受各式各样的字符
- 拿到了项目框架工程代码却没有uml图,那么方法之间的调用关系功能流转就不容易看出来,那么如何产生类图呢,记忆里方法有下:1.rose逆向工程
- 背景SpringBoot bean 加载顺序如何查看,想看加载了哪些bean, 这些bean的加载顺序是什么?实际加载顺序不受控制,但会有一
- 今天我们来讨论如何在项目开发中优雅地使用RocketMQ。本文分为三部分,第一部分实现SpringBoot与RocketMQ的整合,第二部分
- 前言上篇博文把表连接查询和三种对应关系的写法记录总结了,本篇要把 mybatis 中的动态sql 的使用以及缓存知识记录下来。动态SQL在解
- 本文实例讲述了C#将Sql数据保存到Excel文件中的方法,非常有实用价值。分享给大家供大家参考借鉴之用。具体功能代码如下:public s
- 1.介绍说明: 其实@Valid 与 @Validated都是做数据校验的,只不过注解位置与用法有点不同。不同点:(1)@Valid是使用H
- Hadoop环境搭建详见此文章https://www.jb51.net/article/33649.htm。我们已经知道Hadoop能够通过
- 本文介绍了Android BottomSheet效果的两种实现方式,分享给大家,具体如下:BottomSheet效果BottomSheet的
- 前言在SpringBoot中,对于JavaBean的属性一般都绑定在配置文件中,比如application.properties/appli