總結下這幾天Mongodb學習筆記
/**
* 獲取MongoClient
* @author xuyw
* @email [email protected]
* @param host
* @param port
* @return
*/
public static MongoClient getMongoClient(String host, int... port) {
MongoClient mongoClient = null;
int portlen = 0;
try {
if (port != null)
portlen = port.length;
switch (portlen) {
case 0:
if (host != null && !"".equals(host)) {
// 方式二(指定ip):
mongoClient = new MongoClient(host);
} else {
// 直接連接單一mongodb服務器
mongoClient = new MongoClient();
}
break;
case 1:
// 方式二(指定ip、端口):
mongoClient = new MongoClient(host, port[0]);
break;
default:
// 方式三:連接到mongodb服務器集群(會自動發現主服務器)
List list = new ArrayList();
String[] hostip = host.split(",");
for (int i = 0; i < portlen; i++) {
ServerAddress saddress = new ServerAddress(hostip[i],
port[i]);
list.add(saddress);
}
mongoClient = new MongoClient(list);
break;
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
return mongoClient;
}
``/**
* 獲取Db
*
* @param dbname
* @param host
* @param port
* @return
*/
public static DB getDB(String dbname, String host, int... port) {
MongoClient mongoClient = getMongoClient(host, port);
DB db = mongoClient.getDB(dbname);
return db;
}
MongoClient mongoClient = MongoDbUtil.getMongoClient(“192.168.1.101”,
27017);
// 查詢所有的Database
for (String name : mongoClient.getDatabaseNames()) {
System.out.println(“databaseName: ” + name);
}
// 獲取指定數據庫
DB db = mongoClient.getDB(“xuywdb”);
// 查詢所有的聚集集合類似oracle裡面的表名
Set colls = db.getCollectionNames();
for (String s : colls) { System.out.println(s); }
“
//新增2條記錄
public void inserUser(DBCollection t_user) {
DBObject user = new BasicDBObject();
user.put(“username”, “張三”);
user.put(“userage”, 18);
user.put(“usersex”, “男”);
DBObject user2 = new BasicDBObject();
user2.put(“username”, “小紅”);
user2.put(“userage”, 19);
user2.put(“usersex”, “女”);
t_user.insert(user);
t_user.insert(user2);
}
//查詢所有返回一個游標
DBCollection t_user = db.getCollection("t_user");
DBCursor cursor =t_user.find();
while(cursor.hasNext()){
System.out.println(cursor.next());
}
結果輸出
{ "_id" : { "$oid" : "5550bf41d975cf177eab8d1f"} , "username" : "張三" , "userage" : 18 , "usersex" : "男"}
{ "_id" : { "$oid" : "5550bf41d975cf177eab8d20"} , "username" : "小紅" , "userage" : 19 , "usersex" : "女"}
json 操作
DBObject 轉json
JSON.serialize(dBObject )
json轉DBObject
JSON.parse("{ \"name\" : \"xuyw\" , \"age\" : 23}")