package com.roothomes.mongodb.test.bean;
public class MongoDBinfo {
private String ip = "";
private String port = "";
private String defaultDB = "admin";
private String defaultCol = "";
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public String getDefaultDB() {
return defaultDB;
}
public void setDefaultDB(String defaultDB) {
this.defaultDB = defaultDB;
}
public String getDefaultCol() {
return defaultCol;
}
public void setDefaultCol(String defaultCol) {
this.defaultCol = defaultCol;
}
public String toString(){
StringBuffer strb = new StringBuffer();
strb.append("ip:" + ip);
strb.append(" , port:" + port);
strb.append(" , defaultDB:" + defaultDB);
strb.append(" , defaultCol:" + defaultCol);
return strb.toString();
}
}
package com.roothomes.mongodb.test;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.mongodb.BasicDBObject;
import com.mongodb.CommandResult;
import com.mongodb.DB;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.util.JSON;
import com.roothomes.mongodb.test.bean.MongoDBinfo;
public class ThreadInsertData {
public static void main(String[] args) {
MongoDBinfo dbinfo = new MongoDBinfo();
dbinfo.setIp("192.168.1.75");
dbinfo.setPort("20033");
dbinfo.setDefaultDB("roothomesDB");
dbinfo.setDefaultCol("roothomesCol");
try
{
Mongo mongo = new Mongo(dbinfo.getIp() + ":" + dbinfo.getPort());
DB adminDb = mongo.getDB("admin");
List listDb = mongo.getDatabaseNames();
boolean defaultDbflag = false;
boolean defaultColflag = false;
for(String oneDb : listDb){
if(oneDb.equals(dbinfo.getDefaultDB())){
defaultDbflag = true;
Iterator iterCol = adminDb.getCollectionNames().iterator();
while(iterCol.hasNext()){
String colName = iterCol.next();
if(colName.equals(dbinfo.getDefaultCol())){
defaultColflag = true;
}
}
break;
}
}
if(!defaultDbflag){
CommandResult crs = adminDb.command("use " + dbinfo.getDefaultDB());
System.out.println(crs.toString()); // { "errmsg" : "no such cmd: use roothomesDB" , "bad cmd" : { "use roothomesDB" : true} , "ok" : 0.0}
//这里是无法创建DB的,可以再创建集合的时候直接创建DB
}
if(!defaultColflag){
DB db = mongo.getDB(dbinfo.getDefaultDB());
DBObject obj = (BasicDBObject)JSON.parse("{'name':'zouguijin','age':'25'}");
boolean flag = db.collectionExists(dbinfo.getDefaultCol());
if(!flag){
db.createCollection(dbinfo.getDefaultCol(),obj);
System.out.println("创建集合"+ dbinfo.getDefaultCol());
//这里就是创建集合的时候直接创建了DB
}else{
System.out.println("集合"+dbinfo.getDefaultCol()+"已经存在。");
}
//db.roothomesCol.remove({ }); //情况集合
//db.roothomesCol.find().limit(100); //有限制的查询集合
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
阅读(13644) | 评论(0) | 转发(0) |