Util
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 org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.BasicBSONList;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by PeersLee on 2017/1/30.
*/
public class MongoUtil {
public static MongoClient client;
public static MongoDatabase db;
public MongoUtil(String dbName) {
client = new MongoClient("127.0.0.1", 27017);
db = client.getDatabase(dbName);
System.out.println(dbName + "连接成功...");
}
//查找(是否存在)
public boolean isDuplicate(String colName, Map<String, String> map) {
// 默认不重复
boolean res = false;
try {
MongoCollection col = db.getCollection(colName);
Document doc = new Document();
for (Map.Entry<String, String> entry : map.entrySet()) {
doc.append(entry.getKey(), entry.getValue());
}
FindIterable<Document> findIte = col.find(doc);
MongoCursor<Document> mongoCur = findIte.iterator();
if (mongoCur.hasNext()) {
// 如果有元素,则重复
System.out.println("重复...");
res = true;
}
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
return res;
}
//插入(去重复)
public void insertCol(String colName, Map<String, String> msg) {
try {
MongoCollection col = db.getCollection(colName);
// 将msg 中的信息写入
Document doc = new Document();
for(Map.Entry<String, String> entry : msg.entrySet()) {
doc.append(entry.getKey(), entry.getValue());
}
// 创建List
List<Document> docs = new ArrayList<Document>();
docs.add(doc);
col.insertMany(docs);
System.out.println("文档已经插入到" + colName + "...");
} catch (Exception e) {
System.out.println(e.getClass().getName() + ":" + e.getMessage());
}
}
//获取一条数据,并标记处理
public String findOne(String colName, Map<String, String> map, String resKey) {
String res = null;
try {
MongoCollection col = db.getCollection(colName);
// 构造查询条件 doc
Document doc = new Document();
for (Map.Entry<String, String> entry : map.entrySet()) {
doc.append(entry.getKey(), entry.getValue());
}
// 根据 doc(key、value)查询
FindIterable<Document> findIte = col.find(doc);
MongoCursor<Document> mongoCur = findIte.iterator();
if (mongoCur.hasNext()) {
// 根据 resKey 返回字段
res = mongoCur.next().get(resKey).toString();
System.out.println("MongoDB Return:" + res);
} else {
res = null;
System.out.println("MongoDB Return NULL");
}
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
return res;
}
// 更新文档
public void updateOne(String colName, Map<String, String> getMap, Map<String, Object> setMap) {
try {
MongoCollection col = db.getCollection(colName);
// 创建一个List,每个元素是一个比较结果
//extends ArrayList<Object> implements BSONObject
List keys = new BasicBSONList();
for (Map.Entry entry : getMap.entrySet()) {
keys.add(Filters.eq(entry.getKey().toString(), entry.getValue()));
}
// 将上面的Filters List 结合为一个Bson
Bson filters = Filters.and(keys);
// Document
/*
1. Document(Map<String,Object> map)
2. Document(String key, Object value)
3. Document()
*/
col.updateOne(filters, new Document("$set", new Document(setMap)));
//检索查看结果
System.out.println("更新成功...");
} catch (Exception e) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
// 删除一条数据
public void deleteOne(String colName, Map<String, String> map) {
try {
MongoCollection col = db.getCollection(colName);
Document doc = new Document();
for (Map.Entry<String, String> entry : map.entrySet()) {
doc.append(entry.getKey(), entry.getValue());
}
// 删除一条数据
col.deleteOne(doc);
System.out.println("成功删除一条数据!");
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
maven
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.2</version>
</dependency></pre><br>
其他
package com.mkyong.core;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;
/**
* Java MongoDB : Insert a Document
*
*/
public class InsertDocumentApp {
public static void main(String[] args) {
try {
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("yourdb");
DBCollection collection = db.getCollection("dummyColl");
// 1. BasicDBObject example
System.out.println("BasicDBObject example...");
BasicDBObject document = new BasicDBObject();
document.put("database", "mkyongDB");
document.put("table", "hosting");
BasicDBObject documentDetail = new BasicDBObject();
documentDetail.put("records", 99);
documentDetail.put("index", "vps_index1");
documentDetail.put("active", "true");
document.put("detail", documentDetail);
collection.insert(document);
DBCursor cursorDoc = collection.find();
while (cursorDoc.hasNext()) {
System.out.println(cursorDoc.next());
}
collection.remove(new BasicDBObject());
// 2. BasicDBObjectBuilder example
System.out.println("BasicDBObjectBuilder example...");
BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
.add("database", "mkyongDB")
.add("table", "hosting");
BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
.add("records", "99")
.add("index", "vps_index1")
.add("active", "true");
documentBuilder.add("detail", documentBuilderDetail.get());
collection.insert(documentBuilder.get());
DBCursor cursorDocBuilder = collection.find();
while (cursorDocBuilder.hasNext()) {
System.out.println(cursorDocBuilder.next());
}
collection.remove(new BasicDBObject());
// 3. Map example
System.out.println("Map example...");
Map<String, Object> documentMap = new HashMap<String, Object>();
documentMap.put("database", "mkyongDB");
documentMap.put("table", "hosting");
Map<String, Object> documentMapDetail = new HashMap<String, Object>();
documentMapDetail.put("records", "99");
documentMapDetail.put("index", "vps_index1");
documentMapDetail.put("active", "true");
documentMap.put("detail", documentMapDetail);
collection.insert(new BasicDBObject(documentMap));
DBCursor cursorDocMap = collection.find();
while (cursorDocMap.hasNext()) {
System.out.println(cursorDocMap.next());
}
collection.remove(new BasicDBObject());
// 4. JSON parse example
System.out.println("JSON parse example...");
String json = "{'database' : 'mkyongDB','table' : 'hosting'," +
"'detail' : {'records' : 99, 'index' : 'vps_index1', 'active' : 'true'}}}";
DBObject dbObject = (DBObject)JSON.parse(json);
collection.insert(dbObject);
DBCursor cursorDocJSON = collection.find();
while (cursorDocJSON.hasNext()) {
System.out.println(cursorDocJSON.next());
}
collection.remove(new BasicDBObject());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}