package com.mongodb.test;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public final class MongoDB {
public interface MongoObject {
String getName();
void toDocument(Document doc);
}
public interface IdObject extends MongoObject {
String getId();
}
private static MongoDB theInstance = new MongoDB();
private static MongoClient mongo;
private static final String dbName = "local";
private MongoDB() {
}
public static void init(String host, int port, String user, String pwd) {
assert mongo == null;
if (host == null || host.isEmpty())
host = "localhost";
if (port == 0)
port = 27017;
mongo = new MongoClient(host, port);
System.out.println("INFO:init mongodb " + host + " " + port);
}
public static MongoDB getInstance() {
assert mongo != null;
return theInstance;
}
public boolean updateById(IdObject record) {
assert mongo != null;
try {
MongoDatabase db = mongo.getDatabase(dbName);
MongoCollection<Document> collect = db.getCollection(record.getName());
Document select = new Document();
select.put("id", record.getId());
Document doc = new Document();
record.toDocument(doc);
collect.replaceOne(select, doc);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public long checkById(String collectName, String id) {
assert mongo != null;
try {
MongoDatabase db = mongo.getDatabase(dbName);
MongoCollection<Document> collect = db.getCollection(collectName);
Document select = new Document();
select.put("id", id);
long count = collect.count(select);
return count;
}
catch (Exception e) {
e.printStackTrace();
return -1;
}
}
public boolean delById(String collectName, String id) {
assert mongo != null;
try {
MongoDatabase db = mongo.getDatabase(dbName);
MongoCollection<Document> collect = db.getCollection(collectName);
Document select = new Document();
select.put("id", id);
collect.deleteOne(select);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean insert(MongoObject record) {
assert mongo != null;
try {
MongoDatabase db = mongo.getDatabase(dbName);
MongoCollection<Document> collect = db.getCollection(record.getName());
Document doc = new Document();
record.toDocument(doc);
collect.insertOne(doc);
System.out.println("DEBUG:insert OK");
}
catch (Exception e) {
e.printStackTrace();
System.out.println("DEBUG:insert FAILED ****************");
return false;
}
return true;
}
}