mongodb 3.x connect with credential
package mongoDb;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
public class MongoDBUtil {
static MongoClient client;
static DB db;
static DBCollection collection;
static {
try {
// client = new MongoClient("192.168.20.114", 27017);
System.out.println("连接服务器测试.................");
ServerAddress serverAddress = new ServerAddress("localhost", 27017);
List<ServerAddress> seeds = new ArrayList<ServerAddress>();
seeds.add(serverAddress);
MongoCredential credentials = MongoCredential.createMongoCRCredential("abc", "fmr",
"abc".toCharArray());
List<MongoCredential> credentialsList = new ArrayList<MongoCredential>();
credentialsList.add(credentials);
client = new MongoClient(seeds, credentialsList);
// (List<ServerAddress> seeds, List<MongoCredential//
db = client.getDB("fmr");
// db.authenticate("testAdmin", "123".toCharArray());
collection = db.getCollection("user");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void add(DBObject dbObject) {
collection.insert(dbObject);
}
public static void del(DBObject dbObject) {
collection.remove(dbObject);
}
public static void update(DBObject dbObject1, DBObject dbObject2) {
collection.update(dbObject1, dbObject2);
}
public static DBObject queryOneByKey(DBObject dbObject, DBObject keys) {
DBCursor dbCursor = collection.find(dbObject, keys);
if (dbCursor.hasNext()) {
return dbCursor.next();
}
return null;
}
public static java.util.List<DBObject> query(DBObject dbObject) {
DBCursor dbCursor = collection.find(dbObject);
List<DBObject> ret = new ArrayList<DBObject>();
while (dbCursor.hasNext()) {
DBObject dbObject2 = dbCursor.next();
ret.add(dbObject2);
}
return ret;
}
public static void main(String[] args) {
System.out.println(db.collectionExists("poepeo"));
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("num", new BasicDBObject("$gt", 0));
List<DBObject> ret = MongoDBUtil.query(dbObject);
for (Iterator<DBObject> it = ret.iterator(); it.hasNext();) {
System.out.println(it.next());
}
}
}