工具类
package api;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
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 com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
import org.bson.conversions.Bson;
import java.util.ArrayList;
import java.util.List;
/**
* @author jiangli
* @date 2018/4/6 11:48
*/
public class MongoDBUtils {
/**
* 设置数据库连接地址
*/
private static final String CONN_HOST = "127.0.0.1";
/**
* 设置数据库连接端口号
*/
private static final int CONN_PORT = 27017;
/**
* MongoDB连接实例
*/
public MongoClient mongoClient = null;
/**
* MongoDB数据库实例
*/
public MongoDatabase mongoDatabase = null;
/**
* 数据库集合实例
*/
public MongoCollection<Document> coll = null;
/**
* 构造方法
* 获取数据库实例
*
* @param dbName 数据库名称
* @param collName 集合名称
*/
public MongoDBUtils(String dbName, String collName) {
this.mongoClient = new MongoClient(CONN_HOST, CONN_PORT);
this.mongoDatabase = this.mongoClient.getDatabase(dbName);
this.coll = this.mongoDatabase.getCollection(collName);
}
/**
* 创建数据库集合
*
* @param collName 数据库表名
*/
public boolean createCollection(String collName) {
try {
this.mongoDatabase.createCollection(collName);
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
}
return true;
}
/**
* 获取数据库集合
*
* @param collName
* @return
*/
public MongoCollection<Document> getCollection(String collName) {
return this.mongoDatabase.getCollection(collName);
}
/**
* 查找集合内所有Document
*
* @param collName
* @return
*/
public List<Document> findAll(String collName) {
MongoCollection<Document> coll = this.mongoDatabase.getCollection(collName);
List<Document> result = new ArrayList<Document>();
FindIterable<Document> findIterable = coll.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext()) {
result.add(mongoCursor.next());
}
return result;
}
/**
* 指定条件查找
*
* @param query
* @param collName
* @return
*/
public List<Document> findAll(BasicDBObject query, String collName) {
MongoCollection<Document> coll = this.mongoDatabase.getCollection(collName);
List<Document> result = new ArrayList<Document>();
FindIterable<Document> findIterable = coll.find(query);
MongoCursor<Document> mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext()) {
result.add(mongoCursor.next());
}
return result;
}
/**
* 指定条件查找指定字段
*
* @param query
* @param collName
* @return
*/
public List<Document> findAll(BasicDBObject query, BasicDBObject key, String collName) {
MongoCollection<Document> coll = this.mongoDatabase.getCollection(collName);
List<Document> result = new ArrayList<Document>();
FindIterable<Document> findIterable = coll.find(query).projection(key);
MongoCursor<Document> mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext()) {
result.add(mongoCursor.next());
}
return result;
}
/**
* 查找一个
*
* @param query
* @param collName
* @return
*/
public Document findOne(BasicDBObject query, String collName) {
MongoCollection<Document> coll = this.mongoDatabase.getCollection(collName);
Document result = new Document();
FindIterable<Document> findIterable = coll.find(query).limit(1);
result = findIterable.iterator().next();
return result;
}
/**
* 删除集合中的所有数据
*
* @param collName
*/
public void deleteAll(String collName) {
MongoCollection<Document> coll = this.mongoDatabase.getCollection(collName);
BasicDBObject delDbo = new BasicDBObject();
delDbo.append("_id", -1);
DeleteResult deleteResult = coll.deleteMany(Filters.not(delDbo));
long deletedCount = deleteResult.getDeletedCount();
System.out.println(deletedCount>0?"删除"+deletedCount+"条记录":"删除失败");
}
/**
* 删除指定的所有数据
*
* @param b
* @param collName
*/
public void deleteAll(Bson b, String collName) {
MongoCollection<Document> coll = this.mongoDatabase.getCollection(collName);
DeleteResult deleteResult = coll.deleteMany(b);
long deletedCount = deleteResult.getDeletedCount();
System.out.println(deletedCount>0?"删除"+deletedCount+"条记录":"删除失败");
}
/**
* 删除指定的一条数据
*
* @param b
* @param collName
*/
public void deleteOne(Bson b, String collName) {
MongoCollection<Document> coll = this.mongoDatabase.getCollection(collName);
DeleteResult deleteResult = coll.deleteOne(b);
long deletedCount = deleteResult.getDeletedCount();
System.out.println(deletedCount>0?"删除"+deletedCount+"条记录":"删除失败");
}
//collection.updateMany(Filters.eq("likes", 100), new Document("$set", new Document("likes",200)) );
/**
* 按查询条件批量修改
*
* @param b
* @param doc
* @param collName
*/
public void updateAll(Bson b, Document doc, String collName) {
MongoCollection<Document> coll = this.mongoDatabase.getCollection(collName);
UpdateResult updateResult = coll.updateMany(b, doc);
long matchedCount = updateResult.getMatchedCount();
System.out.println(matchedCount>0?"修改"+matchedCount+"条记录":"更新失败");
}
/**
* 按查询条件,修改第一个匹配的文档
*
* @param b
* @param doc
* @param collName
*/
public void updateOne(Bson b, Document doc, String collName) {
MongoCollection<Document> coll = this.mongoDatabase.getCollection(collName);
UpdateResult updateResult = coll.updateOne(b, doc);
long matchedCount = updateResult.getMatchedCount();
System.out.println(matchedCount>0?"修改"+matchedCount+"条记录":"更新失败");
}
/**
* 插入单个文档
*
* @param doc Bson文档
* @param collName 集合名称
*/
public void insert(Document doc, String collName) {
long count1 = coll.count();
coll.insertOne(doc);
long count2 = coll.count();
System.out.println(count2 > count1 ? "新增"+(count2-count1)+"条记录" : "新增失败");
}
/**
* 批量插入文档
*
* @param list List类型文档
* @param collName 集合名称
*/
public void inserts(List<Document> list, String collName) {
long count1 = coll.count();
coll.insertMany(list);
long count2 = coll.count();
System.out.println(count2 > count1 ? "新增"+(count2-count1)+"条记录" : "新增失败");
}
/**
* 关闭连接
* @param mongoClient
*/
public static void close(MongoClient mongoClient) {
mongoClient.close();
}
}
插入演示用的数据
Test类
package api;
import com.mongodb.BasicDBObject;
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;
/**
* @author jiangli
* @date 2018/4/6 11:50
*/
public class Testa {
//数据库名称
private static final String dbName = "shop";
//集合名称
private static final String collName = "shops";
//获取数据库实例
private static final MongoDBUtils mongo = new MongoDBUtils(dbName, collName);
//创建集合
@Test
public void createCollection() {
if (mongo.createCollection(collName)) {
System.out.println("a collection " + dbName + "." + collName + " create success");
} else {
System.out.println("a collection " + dbName + "." + collName + " already exists");
}
}
//查找集合内所有Document
@Test
public void findAll() {
List<Document> list = mongo.findAll(collName);
System.out.println(list.size());
for (Document doc : list) {
System.out.println(doc.toString());
}
}
//指定条件查找全部匹配的文档
@Test
public void findAll1() {
BasicDBObject query = new BasicDBObject();
query.append("name", "iphone0");
List<Document> list = mongo.findAll(query, collName);
System.out.println(list.size());
for (Document doc : list) {
System.out.println(doc.toString());
}
}
//指定条件查找,返回第一个文档
@Test
public void findOne() {
BasicDBObject queryOne = new BasicDBObject();
queryOne.append("name", "iphone0");
Document docOne = mongo.findOne(queryOne, collName);
System.out.println(docOne);
}
//指定条件查找全部匹配的文档,返回指定字段
@Test
public void find1() {
BasicDBObject query = new BasicDBObject();
query.append("name", "iphone0");
BasicDBObject key = new BasicDBObject();
//key:键/字段 val:1返回 0不返回
key.append("name", 1);
key.append("price", 1);
key.append("_id", 0);
List<Document> list = mongo.findAll(query, key, collName);
System.out.println(list.size());
for (Document doc : list) {
System.out.println(doc.toString());
}
}
//删除集合中的所有文档
@Test
public void deleteAll() {
mongo.deleteAll(collName);
}
//按条件删除所有匹配的文档
@Test
public void deleteSome() {
Bson b = Filters.eq("name", "iphone0");
mongo.deleteAll(b, collName);
//按条件删除,第一个匹配的文档
// mongo.deleteOne(b, collName);
}
//按查询条件修改所有匹配的文档
@Test
public void update() {
//查询条件
Bson b = Filters.eq("name", "iphone2");
Document doc = new Document();
//需要修改的键值对,没有就新增
doc.append("address", "China");
doc.append("time", "2018");
doc = new Document("$set", doc);
mongo.updateAll(b, doc, collName);
//按查询条件,修改第一个匹配的文档
//mongo.updateOne(b, doc, collName);
}
@Test
/**
* 插入单个文档
* @param doc Bson文档
* @param collName 集合名称
*/
public void insert() {
Document doc = new Document();
doc.append("name", "iphone0");
doc.append("price", "0");
doc.append("color", "white");
mongo.insert(doc, collName);
}
@Test
/**
* 批量插入文档
* @param list List类型文档
* @param collName 集合名称
*/
public void inserts() {
List<Document> list = new ArrayList<Document>();
for (int i = 0; i < 10; i++) {
Document doc = new Document();
doc.append("name", "iphone" + i);
doc.append("price", i * 100);
doc.append("color", "black" + i);
list.add(doc);
}
mongo.inserts(list, collName);
}
}