1.準(zhǔn)備工作
項(xiàng)目使用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.實(shí)例代碼
代碼之中包括了常見的操作:增刪改查操作稽物。
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 服務(wù)
MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);
//連接到數(shù)據(jù)庫(kù)
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();
}
/**
* 連接需要密碼認(rèn)證的方式
*/
@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);
//通過連接認(rèn)證獲取MongoDB連接
MongoClient mongoClient = new MongoClient(adds, credentials);
//連接到數(shù)據(jù)庫(kù)
MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
System.out.println("connect to mongoDB successfully.");
mongoClient.close();
}
@Test
/**
* 創(chuàng)建集合
*/
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);
//連接到數(shù)據(jù)庫(kù)
MongoDatabase mongoDatabase = mongoClient.getDatabase("test");
logger.info("connect to mongoDB successfully.");
//選擇集合對(duì)象
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.獲取游標(biāo)MongoCursor<Document>
* 3.通過游標(biāo)遍歷檢索出文檔集合
*/
FindIterable<Document> findIterable = collections.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext()) {
logger.info(mongoCursor.next().toJson());
}
mongoClient.close();
}
/**
* 檢索單個(gè)文檔
*/
@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)));
//查看結(jié)果
FindIterable<Document> findIterable=collection.find();
MongoCursor<Document> mongoCursor=findIterable.iterator();
while(mongoCursor.hasNext()){
logger.info(mongoCursor.next().toJson());
}
mongoClient.close();
}
/**
* 刪除第一個(gè)文檔
*/
@Test
public void testRemoveDocument(){
MongoClient mongoClient=new MongoClient("localhost",27017);
MongoDatabase mongoDatabase=mongoClient.getDatabase("test");
MongoCollection<Document> collection=mongoDatabase.getCollection("customers");
//刪除符合條件的第一個(gè)文檔
collection.deleteOne(Filters.eq("like",2001));
//刪除所有符合條件的文檔
collection.deleteMany(Filters.eq("like",20001));
//檢索查看結(jié)果
FindIterable<Document> findIterable=collection.find();
MongoCursor<Document> mongoCursor=findIterable.iterator();
while (mongoCursor.hasNext()){
logger.info(mongoCursor.next().toJson());
}
mongoClient.close();
}
}
3.總結(jié)
使用Java對(duì)MongoDB小試牛刀了一番,MongoDB基于BSON的格式使用起來非常方便折欠,而且擴(kuò)展性好贝或,相對(duì)于關(guān)系型數(shù)據(jù)庫(kù)先定義表后存放數(shù)據(jù),MongoDB有更大的伸縮性锐秦,無須定義表的結(jié)構(gòu)咪奖,存儲(chǔ)數(shù)據(jù)直接創(chuàng)建集合插入數(shù)據(jù)到集合即可,簡(jiǎn)單高效酱床。