import java.util.HashMap;
import java.util.Map;
import com.mongodb.util.JSON;
public class JsonStrToMap {
/**
* json 字符串转化为map格式
* @param jsonString
* @return
*/
public static Map<String, Integer> jsonStrToMap(String jsonString) {
Object parseObj = JSON.parse(jsonString); // 反序列化 把json 转化为对象
Map<String, Integer> map = (HashMap<String, Integer>) parseObj; // 把对象转化为map
return map;
}
}
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
public class MongoHelper {
static final String DBName = "test";
static final String ServerAddress = "127.0.0.1";
static final int PORT = 27017;
public MongoHelper(){
}
public MongoClient getMongoClient( ){
MongoClient mongoClient = null;
try {
// 连接到 mongodb 服务
mongoClient = new MongoClient(ServerAddress, PORT);
System.out.println("Connect to mongodb successfully");
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
return mongoClient;
}
public MongoDatabase getMongoDataBase(MongoClient mongoClient) {
MongoDatabase mongoDataBase = null;
try {
if (mongoClient != null) {
// 连接到数据库
mongoDataBase = mongoClient.getDatabase(DBName);
System.out.println("Connect to DataBase successfully");
} else {
throw new RuntimeException("MongoClient不能够为空");
}
} catch (Exception e) {
e.printStackTrace();
}
return mongoDataBase;
}
public void closeMongoClient(MongoDatabase mongoDataBase,MongoClient mongoClient ) {
if (mongoDataBase != null) {
mongoDataBase = null;
}
if (mongoClient != null) {
mongoClient.close();
}
System.out.println("CloseMongoClient successfully");
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.bson.Document;
import cn.iie.util.JsonStrToMap;
import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
/**
* 实现接口
* @author iiip
*
*/
public class MongoDaoImpl implements MongoDao {
public Map<String, Integer> queryByID(MongoDatabase db, String table, Object Id) throws Exception{
MongoCollection<Document> collection = db.getCollection(table);
BasicDBObject query = new BasicDBObject("id", Id);
// DBObject接口和BasicDBObject对象:表示一个具体的记录,BasicDBObject实现了DBObject,是key-value的数据结构,用起来和HashMap是基本一致的。
FindIterable<Document> iterable = collection.find(query);
// for (Document dd : iterable) {
// int dudu = dd.getInteger("上海"); // 读取响应的数据
// System.out.println("dudududu:"+dudu);
// }
Map<String,Integer> jsonStrToMap = null;
MongoCursor<Document> cursor = iterable.iterator();
while (cursor.hasNext()) {
Document user = cursor.next();
String jsonString = user.toJson();
System.out.println("===查询的结果是:"+jsonString);
jsonStrToMap = JsonStrToMap.jsonStrToMap(jsonString);//这里用到我自己写的方法,主要是包json字符串转换成map格式,为后面做准备,方法放在后面
}
System.out.println("检索ID完毕");
return jsonStrToMap;
}
/**
* 根据一个doc,来检索,当doc是空的时候检索全部
* @param db
* @param table
* @param doc
*/
public List<Map<String,Integer>> queryByDoc(MongoDatabase db, String table, BasicDBObject doc) {
MongoCollection<Document> collection = db.getCollection(table);
FindIterable<Document> iterable = collection.find(doc);
/**
* 1. 获取迭代器FindIterable<Document>
* 2. 获取游标MongoCursor<Document>
* 3. 通过游标遍历检索出的文档集合
* */
List<Map<String,Integer>> list = new ArrayList<Map<String,Integer>>();
MongoCursor<Document> cursor = iterable.iterator();
while (cursor.hasNext()) {
Document user = cursor.next();
String jsonString = user.toJson();
System.out.println("***查询结果:"+jsonString);
Map<String, Integer> jsonStrToMap = JsonStrToMap.jsonStrToMap(jsonString);
list.add(jsonStrToMap);
}
System.out.println("检索doc完毕");
return list;
}
public FindIterable<Document> queryByDocs(MongoDatabase db, String table, BasicDBObject doc) {
MongoCollection<Document> collection = db.getCollection(table);
FindIterable<Document> iterable = collection.find(doc);
System.out.println("检索doc完毕");
return iterable;
}
/**
* 检索全部并返回迭代器
* @param db
* @param table
*/
public List<Map<String,Integer>> queryAll(MongoDatabase db, String table) {
MongoCollection<Document> collection = db.getCollection(table);
FindIterable<Document> iterable = collection.find();
List<Map<String,Integer>> list = new ArrayList<Map<String,Integer>>();
MongoCursor<Document> cursor = iterable.iterator();
while (cursor.hasNext()) {
Document user = cursor.next();
String jsonString = user.toJson();
System.out.println("======查询结果:"+jsonString);
Map<String, Integer> jsonStrToMap = JsonStrToMap.jsonStrToMap(jsonString);
list.add(jsonStrToMap);
}
System.out.println("检索全部完毕");
return list;
}
/*
*
*
*/
public FindIterable<Document> queryAlls(MongoDatabase db, String table) {
MongoCollection<Document> collection = db.getCollection(table);
FindIterable<Document> iterable = collection.find();
/*List<Map<String,Integer>> list = new ArrayList<Map<String,Integer>>();
MongoCursor<Document> cursor = iterable.iterator();
while (cursor.hasNext()) {
Document user = cursor.next();
String jsonString = user.toJson();
System.out.println("======查询结果:"+jsonString);
Map<String, Integer> jsonStrToMap = JsonStrToMap.jsonStrToMap(jsonString);
list.add(jsonStrToMap);
}*/
System.out.println("检索全部完毕");
return iterable;
}
/**
* 便利迭代器FindIterable<Document>
*/
public void printFindIterable(FindIterable<Document> iterable){
MongoCursor<Document> cursor = iterable.iterator();
while (cursor.hasNext()) {
Document user = cursor.next();
System.out.println("======usser:"+user.toJson());
}
cursor.close();
}
public boolean insert(MongoDatabase db, String table, Document document) {
MongoCollection<Document> collection = db.getCollection(table);
collection.insertOne(document);
long count = collection.count(document);
/*System.out.println(collection.getNamespace());//weibo.area
System.out.println(collection.getClass());//class com.mongodb.MongoCollectionImpl
System.out.println(collection.getDocumentClass());//class org.bson.Document
System.out.println(collection.getWriteConcern());//WriteConcern{w=1, wtimeout=0, fsync=false, j=false
System.out.println(collection.getWriteConcern().getW());//1
*/
System.out.println("count: "+count);
if(count == 1){
System.out.println("文档插入成功");
return true;
}else{
System.out.println("文档插入成功");
return false;
}
}
/**
* insert many
* @param db
* @param table
* @param document
*/
public boolean insertMany(MongoDatabase db, String table, List<Document> documents ) {
MongoCollection<Document> collection = db.getCollection(table);
long preCount = collection.count();
collection.insertMany(documents);
long nowCount = collection.count();
System.out.println("插入的数量: "+(nowCount-preCount));
if((nowCount-preCount) == documents.size() ){
System.out.println("文档插入多个成功");
return true;
}else{
System.out.println("文档插入多个失败");
return false;
}
}
public boolean delete(MongoDatabase db, String table, BasicDBObject document) {
MongoCollection<Document> collection = db.getCollection(table);
DeleteResult deleteManyResult = collection.deleteMany(document);
long deletedCount = deleteManyResult.getDeletedCount();
System.out.println("删除的数量: "+deletedCount);
if(deletedCount > 0){
System.out.println("文档删除多个成功");
return true;
}else{
System.out.println("文档删除多个失败");
return false;
}
}
/**
* 删除一个
* @param db
* @param table
* @param document
*/
public boolean deleteOne(MongoDatabase db, String table, BasicDBObject document) {
MongoCollection<Document> collection = db.getCollection(table);
DeleteResult deleteOneResult = collection.deleteOne(document);
long deletedCount = deleteOneResult.getDeletedCount();
System.out.println("删除的数量: "+deletedCount);
if(deletedCount == 1){
System.out.println("文档删除一个成功");
return true;
}else{
System.out.println("文档删除一个失败");
return false;
}
}
public boolean update(MongoDatabase db, String table, BasicDBObject whereDoc,BasicDBObject updateDoc) {
MongoCollection<Document> collection = db.getCollection(table);
UpdateResult updateManyResult = collection.updateMany(whereDoc, new Document("$set",updateDoc));
long modifiedCount = updateManyResult.getModifiedCount();
System.out.println("修改的数量: "+modifiedCount);
if (modifiedCount > 0){
System.out.println("文档更新多个成功");
return true;
}else{
System.out.println("文档更新失败");
return false;
}
}
/**
* update one Data
* @param db
* @param table
* @param whereDoc
* @param updateDoc
*/
public boolean updateOne(MongoDatabase db, String table, BasicDBObject whereDoc,BasicDBObject updateDoc) {
MongoCollection<Document> collection = db.getCollection(table);
UpdateResult updateOneResult = collection.updateOne(whereDoc, new Document("$set",updateDoc));
long modifiedCount = updateOneResult.getModifiedCount();
System.out.println("修改的数量: "+modifiedCount);
if(modifiedCount == 1){
System.out.println("文档更新一个成功");
return true;
}else{
System.out.println("文档更新失败");
return false;
}
}
/**
* create collection
* @param db
* @param table
*/
public void createCol(MongoDatabase db, String table) {
db.createCollection(table);
System.out.println("集合创建成功");
}
/**
* drop a collection
* @param db
* @param table
*/
public void dropCol(MongoDatabase db, String table) {
db.getCollection(table).drop();
System.out.println("集合删除成功");
}
}
import java.util.Map;
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoDatabase;
/**
* Dao 层接口
*
*/
public interface MongoDao {
/**
* Get Data BY ID
*
* @param db
* @param table
* @param Id
* @throws Exception
*/
public Map<String,Integer> queryByID(MongoDatabase db, String table, Object Id) throws Exception;
/**
* Insert Data
*
* @param db
* @param table
* @param document
*/
public boolean insert(MongoDatabase db, String table, Document doc);
/**
* Delete Many Data.if doc is empty will delete all Data
*
* @param db
* @param table
* @param document
*/
public boolean delete(MongoDatabase db, String table, BasicDBObject doc);
/**
* Update All Data
*
* @param db
* @param table
* @param oldDoc
* @param newDoc
*/
public boolean update(MongoDatabase db, String table, BasicDBObject oldDoc,
BasicDBObject newDoc);
}
package DaoTest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import net.sf.json.JSONObject;
import org.bson.Document;
import cn.iie.MongoHelper;
import cn.iie.dao.MongoDaoImpl;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoDatabase;
import com.mongodb.util.JSON;
/**
* 测试类
* @author koo
*
*/
public class MainMonHelperImpl {
public static void main(String[] args) {
MongoHelper mongoHelper = new MongoHelper();
MongoClient mongoClient = mongoHelper.getMongoClient();
MongoDatabase mongoDataBase = mongoHelper.getMongoDataBase(mongoClient);
MongoDaoImpl mongoDaoImpl = new MongoDaoImpl();
String table="wb";
// * 直接用BasicDBObject进行CRUD
Map<String, Object> areaMap = new HashMap<String,Object>();
areaMap.put("_id", 2);
areaMap.put("北京", 5);
areaMap.put("上海", 14);
areaMap.put("广州",8);
areaMap.put("深圳",0.5);
// mongoDaoImpl.insert(mongoDataBase, table, new Document(areaMap));//插入document
/*try {
Map<String, Integer> map=mongoDaoImpl.queryByID(mongoDataBase, table, 111);
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*///检索event_id,注意id类型是字符串还是int
/* BasicDBObject document2 = new BasicDBObject("id",111);
document2.append("id", 112);//会覆盖掉111
List<Map<String,Integer>> lm= mongoDaoImpl.queryByDoc(mongoDataBase, table, document2);//检索doc,可以根据doc(key,value)来查找,当doc是空的时候,检索全部
for (Map<String, Integer> map : lm) {
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
}
List<Map<String,Integer>>lall=mongoDaoImpl.queryAll(mongoDataBase, table); //查询全部
for (Map<String, Integer> map : lall) {
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
}*/
/* BasicDBObject document3 = new BasicDBObject("id",120);
Boolean b= mongoDaoImpl.delete(mongoDataBase, table, document3);//删除doc 的全部信息,当doc 是空,则删除全部
System.out.println("=====结果:"+b);*/
/*BasicDBObject document3 = new BasicDBObject("likes", 1000);
mongoDaoImpl.deleteOne(mongoDataBase, table, document3);//删除doc 的一个信息
*/
// 更新文档 将文档中likes=100的文档修改为likes=200
// BasicDBObject whereDoc = new BasicDBObject("北京",255);
// BasicDBObject updateDoc = new BasicDBObject("北京",250);
// mongoDaoImpl.update(mongoDataBase, table, whereDoc, updateDoc);//更新全部,查找到oldDoc的数据,更新newDoc的数据
// BasicDBObject whereDoc = new BasicDBObject("likes",255);
// BasicDBObject updateDoc = new BasicDBObject("event_id",205);
// mongoDaoImpl.updateOne(mongoDataBase, table, whereDoc, updateDoc);//更新全部,查找到oldDoc的数据,更新newDoc的数据
//------------------------------------------------
/**
* 使用map 进行CRUD操作
*/
System.out.println("测试map");
Map<String, Object> areaMap1 = new HashMap<String,Object>();
areaMap1.put("_id", 4);
areaMap1.put("北京", 5);
areaMap1.put("上海", 14);
areaMap1.put("广州",8);
areaMap1.put("深圳",0.5);
//把map反序列化
System.out.println("map parse: " + JSON.parse(JSON.serialize(areaMap)));
String areaTable="wb";
// 根据map 到mongodb查询
/* FindIterable<Document> queryByDocResult = mongoDaoImpl.queryByDocs(mongoDataBase, areaTable, new BasicDBObject(areaMap1));
for (Document document : queryByDocResult) {
System.out.println("======document:"+document);
Integer id=document.getInteger("_id");
Integer sh=document.getInteger("上海");
System.out.println("====id:"+id+",sh:"+sh);
}
mongoDaoImpl.printFindIterable(queryByDocResult);*/
// 插入map 到mongodb
//mongoDaoImpl.insert(mongoDataBase, areaTable, new Document(areaMap1));
/*Map<String, Object> areaMap2 = new HashMap<String,Object>();
Map<String, Object> areaMap3 = new HashMap<String,Object>();
areaMap2.put("_id", 10);
areaMap2.put("北京", 5);
areaMap3.put("_id", 11);
areaMap3.put("北京", 5);*/
/*JSONObject obj=new JSONObject();
obj.put("_id", 11);
obj.put("北京", 5.2);
JSONObject obj1=new JSONObject();
obj.put("_id", 12);
obj.put("北京", 5.3);*/
/* List<Document> docList = new ArrayList<Document>();
docList.add(new Document().parse(obj.toString()));
docList.add(new Document().parse(obj1.toString()));
docList.add(new Document(areaMap2));
docList.add(new Document(areaMap3));*/
//mongoDaoImpl.insertMany(mongoDataBase, areaTable, docList);
// 根据map 删除mongodb
//mongoDaoImpl.delete(mongoDataBase, areaTable, new BasicDBObject(areaMap1));
// mongoDaoImpl.deleteOne(mongoDataBase, areaTable, new BasicDBObject(areaMap1));
//根据map 更新mongodb
/*Map<String, Object> updateDoc = new HashMap<String,Object>();
Map<String, Object> wehereDoc = new HashMap<String,Object>();
wehereDoc.put("上海",14);
updateDoc.put("北京",777);
mongoDaoImpl.update(mongoDataBase, areaTable, new BasicDBObject(wehereDoc), new BasicDBObject(updateDoc));
mongoDaoImpl.updateOne(mongoDataBase, areaTable, new BasicDBObject(wehereDoc), new BasicDBObject(updateDoc));*/
//检索全部
/* FindIterable<Document> queryAllResult = mongoDaoImpl.queryAlls(mongoDataBase, areaTable);
mongoDaoImpl.printFindIterable(queryAllResult);*/
mongoHelper.closeMongoClient(mongoDataBase,mongoClient);
}
}
所需要的包
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.0.4</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.0.4</version>
</dependency>
</dependencies>