java操作mongodb_Java操作MongoDB实现CRUD

本文介绍了如何在Java环境下使用MongoDB,包括创建Maven项目、添加MongoDB驱动依赖,以及实现验证和未验证连接MongoDB的工具类。接着通过JUnit测试类展示了MongoDB的CRUD操作,包括插入、更新、删除和查询文档。
摘要由CSDN通过智能技术生成

开发环境

1、Mac

2、IDEA

3、MongoDB 3.6.5

4、Maven

项目实例

1、创建Maven项目mongodb_test,这里不废话

2、pom.xml添加jar依赖,这里用到了两个jar:mongo-java-driver:3.7.0(尽量和你MongoDB版本一致),Junit4.7(我用到了Junit,没用可以不引)

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

mongodb_test

mongodb_test

1.0-SNAPSHOT

http://maven.apache.org

org.mongodb

mongo-java-driver

3.7.0

junit

junit

4.7

test

3、创建MongoDB连接工具类 MongoConnection,其中有两种连接方式:验证用户名+密码,不验证用户名+密码;

package connection;

import com.mongodb.MongoClient;

import com.mongodb.MongoCredential;

import com.mongodb.ServerAddress;

import com.mongodb.client.MongoDatabase;

import java.util.ArrayList;

import java.util.List;

/**

* MongoDB连接工具类

* @author lihaoshan

* @date 2018-05-30

* */

public class MongoConnection {

/**

* 需要验证用户名、密码的连接方式

* @return mongoDatabase

* */

public MongoDatabase getConnection(){

try{

//连接到MongoDB服务,如果是远程连接可以将localhost改为服务器所在的IP地址

//ServerAddress()参数分别为服务器地址、端口

ServerAddress serverAddress = new ServerAddress("localhost",27017);

List serverAddressList = new ArrayList();

serverAddressList.add(serverAddress);

//createScramSha1Credential()参数分别为用户名、数据库名称、密码

MongoCredential mongoCredential = MongoCredential.createScramSha1Credential("userName","databaseName","password".toCharArray());

List mongoCredentialList = new ArrayList();

mongoCredentialList.add(mongoCredential);

//通过连接认证获取MongoDB连接

MongoClient mongoClient = new MongoClient(serverAddressList,mongoCredentialList);

//连接数据库

MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");

System.out.println("MongoDB连接成功");

return mongoDatabase;

} catch (Exception e){

System.err.println(e.getClass().getName() + ": " + e.getMessage());

}

return null;

}

/**

* 不需要验证用户名、密码的连接方式

* @return mongoDatabase

* */

public MongoDatabase getConnectionBasis(){

try{

//连接到MongoDB服务

MongoClient mongoClient = new MongoClient("localhost",27017);

MongoDatabase mongoDatabase = mongoClient.getDatabase("users");

System.out.println("MongoDB连接成功");

return mongoDatabase;

} catch (Exception e){

System.out.println(e.getClass().getName() + ":" + e.getMessage());

}

return null;

}

}

4、创建junit测试类 MongoDBTest,其中方法为MongoDB的CRUD操作

import com.mongodb.client.FindIterable;

import com.mongodb.client.MongoCollection;

import com.mongodb.client.MongoCursor;

import com.mongodb.client.MongoDatabase;

import com.mongodb.client.model.Filters;

import connection.MongoConnection;

import org.bson.Document;

import org.junit.Test;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.List;

/**

* MongoDB 测试

* @author lihaoshan

* @date 2018-05-30

* */

public class MongoDBTest {

MongoConnection mongoConnection = new MongoConnection();

//连接数据库(不需要验证用户名、密码方式)

MongoDatabase mongoDatabase = mongoConnection.getConnectionBasis();

@Test

public void test(){

MongoCollection documentCollection = getCollection();

//新增文档

// insertDomcument(documentCollection);

//更新文档

// update(documentCollection);

//删除文档

// delete(documentCollection);

//查询所有文档

findAll(documentCollection);

}

/**

* 获取 集合【对应RDBMS 中的数据表】com.mongodb.client.MongoDatabase.getCollection("集合名")

*/

public MongoCollection getCollection(){

MongoCollection collection = mongoDatabase.getCollection("users");

System.out.println("转换到指定集合");

return collection;

}

/**

* 插入文档

* */

public void insertDomcument(MongoCollection collection){

//创建文档对象com.bson.Document 参数为key-value格式

Document document = new Document();

document.append("name","李汶泽");

document.append("age","28");

List documentList = new ArrayList();

documentList.add(document);

collection.insertMany(documentList);

System.out.println("插入文档成功");

}

/**

* 更新 所有文档【表内 数据】com.mongodb.client.MongoCollection.updateMany()

*/

public void update(MongoCollection collection){

collection.updateMany(Filters.eq("age", 100), new Document("$set",new Document("age",30)));

FindIterable findIterable = collection.find();

MongoCursor cursor = findIterable.iterator();

while (cursor.hasNext()) {

System.out.println("更新后的MongoDB数据:"+cursor.next());

}

}

/**

* 删除 文档 com.mongodb.client.MongoCollection.deleteMany()/deleteOne()

*/

public void delete(MongoCollection collection){

// 删除符合条件的 第一个文档

collection.findOneAndDelete(Filters.eq("age", 26));

//删除符合条件的 所有文档

// collection.deleteMany(Filters.gte("age", 20));

FindIterable findIterable = collection.find();

MongoCursor cursor = findIterable.iterator();

while(cursor.hasNext()){

System.out.println("删除后的MongoDB数据:"+cursor.next());

}

}

/**

* 查询 所有文档【表内 数据】com.mongodb.client.MongoCollection.find()

* 查询 本条数据的时间节点 _id采用ObjectId格式

*

* ObjectId 是一个12字节 BSON 类型数据,有以下格式:

* 前4个字节表示时间戳

* 接下来的3个字节是机器标识码

* 紧接的两个字节由进程id组成(PID)

* 最后三个字节是随机数。

*/

public void findAll(MongoCollection collection){

/**

* 1. 获取迭代器FindIterable

* 2. 获取游标MongoCursor

* 3. 通过游标遍历检索出的文档集合

* */

FindIterable findIterable = collection.find();

MongoCursor mongoCursor = findIterable.iterator();

while(mongoCursor.hasNext()){

Document document = mongoCursor.next();

System.out.println("MongoDB数据:"+document);

System.out.println("插入时间:"+new SimpleDateFormat().format(document.getObjectId("_id").getDate()));

}

}

}

5、到这里MongoDB的CRUD简单操作就基本完成了,其他的后续再补充;

码云

https://gitee.com/haoshan/mongodb_test

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值