1.准备工作
项目使用maven搭建,所以首要的工作需要加入mongodb的依赖,这里mongo-java-driver使用的是3.3.0的版本,bson依赖是mongoDB提供的BSON操作工具。
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>bson</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.3.0</version>
</dependency>
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<Document> collection=mongoDatabase.getCollection("customers");
FindIterable<Document> findIterable=collection.find(new Document("id",9527));
MongoCursor<Document> 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<ServerAddress> adds = new ArrayList<ServerAddress>();
adds.add(serverAddress);
MongoCredential credential = MongoCredential.createScramSha1Credential("username", "dbName", "password".toCharArray());
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
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<Document> collections = mongoDatabase.getCollection("customers");
//插入文档
Document doc = new Document("title", "MongoDB")
.append("description", "Nosql Database")
.append("lke", 100)
.append("by", "peter");
List<Document> docs = new ArrayList<Document>();
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<Document> collections = mongoDatabase.getCollection("customers");
/**
* 检索所有文档
*
* 1.获取迭代器FindIterable<Document>
* 2.获取游标MongoCursor<Document>
* 3.通过游标遍历检索出文档集合
*/
FindIterable<Document> findIterable = collections.find();
MongoCursor<Document> 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<Document> collections = mongoDatabase.getCollection("customers");
FindIterable<Document> findIterable = collections.find(new Document("id",9527));
MongoCursor<Document> 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<Document> collection=mongoDatabase.getCollection("customers");
//更新文档,将文档中id=2的文档修改为id=9527
collection.updateMany(Filters.eq("id",2),new Document("$set",new Document("id",9527)));
//查看结果
FindIterable<Document> findIterable=collection.find();
MongoCursor<Document> 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<Document> collection=mongoDatabase.getCollection("customers");
//删除符合条件的第一个文档
collection.deleteOne(Filters.eq("like",2001));
//删除所有符合条件的文档
collection.deleteMany(Filters.eq("like",20001));
//检索查看结果
FindIterable<Document> findIterable=collection.find();
MongoCursor<Document> mongoCursor=findIterable.iterator();
while (mongoCursor.hasNext()){
logger.info(mongoCursor.next().toJson());
}
mongoClient.close();
}
}
3.总结
使用Java对MongoDB小试牛刀了一番,MongoDB基于BSON的格式使用起来非常方便,而且扩展性好,相对于关系型数据库先定义表后存放数据,MongoDB有更大的伸缩性,无须定义表的结构,存储数据直接创建集合插入数据到集合即可,简单高效。