java+mongodb小例子,Java+MongoDB初探

本文介绍了使用Java进行MongoDB数据库的操作,包括连接MongoDB、增删改查基本操作,以及密码认证的实现。示例代码详细展示了如何执行常见数据库操作,如创建集合、插入文档、检索所有和单个文档、更新和删除文档,体现了MongoDB基于BSON的便捷性和灵活性。
摘要由CSDN通过智能技术生成

1.准备工作

项目使用maven搭建,所以首要的工作需要加入mongodb的依赖,这里mongo-java-driver使用的是3.3.0的版本,bson依赖是mongoDB提供的BSON操作工具。

org.mongodb

bson

3.3.0

org.mongodb

mongo-java-driver

3.3.0

2.实例代码

代码之中包括了常见的操作:增删改查操作。

import com.mongodb.MongoClient;

import com.mongodb.MongoCredential;

import com.mongodb.ServerAddress;

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 org.bson.Document;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.ArrayList;

import java.util.List;

/**

* Created by veione on 2016/12/3.

*/

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations = "classpath:spring/applicationContext.xml")

public class MongoDBTest {

private static final Logger logger = LoggerFactory.getLogger(MongoDBTest.class);

@Test

public void testConnectMongoDB() {

// 连接到 mongodb 服务

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

//连接到数据库

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

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

FindIterable findIterable=collection.find(new Document("id",9527));

MongoCursor mongoCursor=findIterable.iterator();

while (mongoCursor.hasNext()){

logger.info(mongoCursor.next().toJson());

}

mongoClient.close();

}

/**

* 连接需要密码认证的方式

*/

@Test

public void testNeedAuthConnectDB() {

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

List adds = new ArrayList();

adds.add(serverAddress);

MongoCredential credential = MongoCredential.createScramSha1Credential("username", "dbName", "password".toCharArray());

List credentials = new ArrayList();

credentials.add(credential);

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

MongoClient mongoClient = new MongoClient(adds, credentials);

//连接到数据库

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

System.out.println("connect to mongoDB successfully.");

mongoClient.close();

}

@Test

/**

* 创建集合

*/

public void testCreateCollection() {

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

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

mongoDatabase.createCollection("goods");

System.out.println("create collection successfully.");

mongoClient.close();

}

/**

* 插入文档操作

*/

@Test

public void testInsertDocument() {

// Connect to the mongoDB

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

//连接到数据库

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

logger.info("connect to mongoDB successfully.");

//选择集合对象

MongoCollection collections = mongoDatabase.getCollection("customers");

//插入文档

Document doc = new Document("title", "MongoDB")

.append("description", "Nosql Database")

.append("lke", 100)

.append("by", "peter");

List docs = new ArrayList();

docs.add(doc);

collections.insertMany(docs);

logger.info("insert document successfully.");

mongoClient.close();

}

/**

* 检索所有文档

*/

@Test

public void testSearchAllDocuments() {

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

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

MongoCollection collections = mongoDatabase.getCollection("customers");

/**

* 检索所有文档

*

* 1.获取迭代器FindIterable

* 2.获取游标MongoCursor

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

*/

FindIterable findIterable = collections.find();

MongoCursor mongoCursor = findIterable.iterator();

while (mongoCursor.hasNext()) {

logger.info(mongoCursor.next().toJson());

}

mongoClient.close();

}

/**

* 检索单个文档

*/

@Test

public void testSearchSingleDocument(){

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

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

MongoCollection collections = mongoDatabase.getCollection("customers");

FindIterable findIterable = collections.find(new Document("id",9527));

MongoCursor mongoCursor = findIterable.iterator();

while (mongoCursor.hasNext()) {

logger.info(mongoCursor.next().toJson());

}

mongoClient.close();

}

/**

* 更新文档

*/

@Test

public void testUpdateDocument(){

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

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

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

//更新文档,将文档中id=2的文档修改为id=9527

collection.updateMany(Filters.eq("id",2),new Document("$set",new Document("id",9527)));

//查看结果

FindIterable findIterable=collection.find();

MongoCursor mongoCursor=findIterable.iterator();

while(mongoCursor.hasNext()){

logger.info(mongoCursor.next().toJson());

}

mongoClient.close();

}

/**

* 删除第一个文档

*/

@Test

public void testRemoveDocument(){

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

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

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

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

collection.deleteOne(Filters.eq("like",2001));

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

collection.deleteMany(Filters.eq("like",20001));

//检索查看结果

FindIterable findIterable=collection.find();

MongoCursor mongoCursor=findIterable.iterator();

while (mongoCursor.hasNext()){

logger.info(mongoCursor.next().toJson());

}

mongoClient.close();

}

}

3.总结

使用Java对MongoDB小试牛刀了一番,MongoDB基于BSON的格式使用起来非常方便,而且扩展性好,相对于关系型数据库先定义表后存放数据,MongoDB有更大的伸缩性,无须定义表的结构,存储数据直接创建集合插入数据到集合即可,简单高效。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值