Java與mongodb的連接
1. 連單臺(tái)mongodb
Mongo mg = new Mongo();//默認(rèn)連本機(jī)127.0.0.1 端口為27017
Mongo mg = new Mongo(ip);//可以指定ip 端口默認(rèn)為27017
Mongo mg = new Mongo(ip,port);//也可以指定ip及端口
2. 連雙臺(tái)mongodb
//ip為主機(jī)ip地址,port為端口號(hào),dataBaseName相當(dāng)于數(shù)據(jù)庫(kù)名
DBAddress left = new DBAddress("ip:port/dataBaseName");
DBAddress right = new DBAddress("ip:port/dataBaseName ");
//若一個(gè)mongodb出現(xiàn)問(wèn)題,會(huì)自動(dòng)連另外一臺(tái)
Mongo mongo = new Mongo(left, right);
3. 連多臺(tái)mongodb
ListServerAddress> mongoHostList = new ArrayListServerAddress>();
mongoHostList.add(new ServerAddress("ip",port));
mongoHostList.add(new ServerAddress("ip",port));
mongoHostList.add(new ServerAddress("ip",port));
Mongo mg = new Mongo(mongoHostList);
Java獲取mongodb的數(shù)據(jù)庫(kù)名
1. 獲取mongodb的db(數(shù)據(jù)庫(kù))
//dataBaseName相當(dāng)于關(guān)系數(shù)據(jù)庫(kù)里的數(shù)據(jù)庫(kù)名,mongodb中若沒(méi)有該
//數(shù)據(jù)庫(kù)名也不會(huì)報(bào)錯(cuò),默認(rèn)mongodb會(huì)建立這個(gè)數(shù)據(jù)庫(kù)名,為空。
DB db = mg.getDB(dataBaseName);
注意:mongodb區(qū)分大小寫(xiě),程序中一定要注意
2.mongodb的db安全認(rèn)證
//安全認(rèn)證java代碼 返回true表示通過(guò),false表示沒(méi)通過(guò)不能進(jìn)行操作
db.authenticate("userName", "password".toCharArray());
if(db.authenticate("admin", "123".toCharArray())){
System.out.println("連接mongodb成功...");
} else{
System.out.println("連接mongodb失敗...");
}
Java對(duì)mongodb的collection進(jìn)行crud操作
1.得到mongodb中的db的collection(表)
//參數(shù)tableName相當(dāng)于關(guān)系數(shù)據(jù)庫(kù)里的表名,
//若mongodb中沒(méi)有該tableName,默認(rèn)會(huì)創(chuàng)建該tableName,為空
DBCollection users = db.getCollection(tableName);
//列出庫(kù)的集合列表,相對(duì)于表對(duì)象
SetString> colls = db.getCollectionNames();
for(String s : colls){
}
// 獲取單個(gè)集合
DBCollection con = db.getCollection("users");
2.mongodb中的db的collection自增長(zhǎng)主鍵
Mongodb中也像傳統(tǒng)的關(guān)系數(shù)據(jù)庫(kù)里表一樣,有主鍵(_id)概念,用來(lái)唯一標(biāo)識(shí)他們。當(dāng)用戶(hù)往collection中插入一條新記錄的時(shí)候,如果沒(méi)有指定_id屬性,那么mongodb會(huì)自動(dòng)生成一個(gè)ObjectId類(lèi)型的值,保存為_(kāi)id的值。
_id的值可以為任何類(lèi)型,除了數(shù)組,在實(shí)際應(yīng)用中,鼓勵(lì)用戶(hù)自己定義_id值,但是要保證他的唯一性。
傳統(tǒng)的數(shù)據(jù)庫(kù)中,通常用一個(gè)遞增的序列來(lái)提供主鍵,在Mongodb中用ObjectId來(lái)代替,我們可以通過(guò)如下的方法來(lái)得到主鍵。
public class Tools {
/**
* 實(shí)現(xiàn)mongodb主鍵自增長(zhǎng)的功能
* @param users
* @param tableName
* @return
*/
public static long getNext(DBCollection users,String tableName){
long incId = 0;
try {
DBObject ret = users.findAndModify(
new BasicDBObject("_id", tableName), null, null, false,
new BasicDBObject("$inc", new BasicDBObject("next", 1)),
true, true);
incId = Long.valueOf(ret.get("next").toString());
} catch (Exception e) {
e.printStackTrace();
}
return incId;
}
}
3.java對(duì)collection進(jìn)行插入操作
DB db = m.getDB("testdb");
DBCollection con = db.getCollection("users");
//普通添加
BasicDBObject doc = new BasicDBObject();
doc.put("name", "MongoDB");
doc.put("type", "database");
doc.put("count", 1);
BasicDBObject info = new BasicDBObject();
info.put("x", 203);
info.put("y", 102);
doc.put("info", info);
con.insert(doc); //插入對(duì)象
//特殊添加
// 添加多個(gè)特殊數(shù)據(jù)(模式自由)
for(int i = 1; i =20; i++){
con.insert(new BasicDBObject().append("i", i));
}
DBObject user_json = (DBObject)JSON.parse("{'user':[{'name':'AAA', 'age':'18'},{'name':'BBB', 'age':'19'}]}");
con.insert(user_json);
//添加JAVA對(duì)象
// 添加java對(duì)象,對(duì)象要序列化Serializable接口
UserInfo userinfo = new UserInfo("用戶(hù)甲AA", 1);
User user = new User(1, "123", userinfo);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(os);
out.writeObject(user);
os.close(); out.close();
con.insert(MonGoUtil.insertObject("user_info",os.toByteArray()));
ListUserInfo> list = new ArrayListUserInfo>();
list.add(new UserInfo("List1", 1));
list.add(new UserInfo("List2", 2));
list.add(new UserInfo("List3", 3));
ByteArrayOutputStream os = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(os);
out.writeObject(list);
os.close(); out.close();
con.insert(MonGoUtil.insertObject("lists",os.toByteArray()));
4.java對(duì)collection的查詢(xún)操作
/** 輸出獲取到的文檔 **/
public static void showDBCursor(DBCursor cur){
while(cur.hasNext()){
System.out.println(cur.next());
}
System.out.println();
}
高級(jí)查詢(xún)
//查詢(xún)_id為30000 返回cust_Id的值 ,mongodb查詢(xún)都會(huì)返回主鍵的值
System.out.println(users.findOne(new BasicDBObject("_id",30000),new BasicDBObject("cust_Id",true)));
findAndRemove() 查詢(xún)_id=30000的數(shù)據(jù),并且刪除
users.findAndRemove(new BasicDBObject("_id", 30000));
findAndModify介紹
users.findAndModify(
new BasicDBObject("_id", 28), //查詢(xún)_id=28的數(shù)據(jù)
new BasicDBObject("cust_Id", true), //查詢(xún)cust_Id屬性
new BasicDBObject("notice_Id", true), //按照notice_Id排序
false, //查詢(xún)到的記錄是否刪除,true表示刪除
new BasicDBObject("province_Id", "100"), //將province_id的值改為100
true, //是否返回新記錄 true返回,false不返回
true //如果沒(méi)有查詢(xún)到該數(shù)據(jù)是否插collection true入庫(kù),false不入
));
查詢(xún)所有數(shù)據(jù)
//列出所有文檔
BasicDBObject query = new BasicDBObject();
System.out.println("列出"+ con.getName() +"集合(表)的所有文檔...");
showDBCursor(con.find());
查詢(xún)JAVA對(duì)象
String key = "user_info";
BasicDBObject query = new BasicDBObject();
query.put(key, new BasicDBObject("$exists", true));
byte[] b = (byte[])con.findOne(query).get(key);
InputStream inputStream = new ByteArrayInputStream(b);
ObjectInputStream in = new ObjectInputStream(inputStream);
User users = (User) in.readObject();
System.out.println("用戶(hù)對(duì)象_json:" + JSONArray.fromObject(users));
單一條件查詢(xún)(數(shù)字)
BasicDBObject query = new BasicDBObject();
query.put("i", 11);
showDBCursor(con.find(query));
單一條件查詢(xún)(字符串)
BasicDBObject query = new BasicDBObject();
query.put("name", "MongoDB");
showDBCursor(con.find(query));
$ne非等于查詢(xún)
BasicDBObject query = new BasicDBObject();
query.put("name", new BasicDBObject("$ne", "MongoDB"));
showDBCursor(con.find(query));
根據(jù)列名查詢(xún)
System.out.println("查詢(xún)有'type'字段的數(shù)據(jù)..."); // false表示沒(méi)有
BasicDBObject query = new BasicDBObject();
query.put("type", new BasicDBObject("$exists", true)); // false
showDBCursor(con.find(query));
單字段and查詢(xún)
System.out.println("單字段and條件的使用,i>=2 and i5 ,i:[2,5)...");
BasicDBObject query = new BasicDBObject();
query.put("i", new BasicDBObject("$gte", 2).append("$lt", 5));
showDBCursor(con.find(query));
多字段and查詢(xún)
BasicDBObject query = new BasicDBObject();();
query.put("name", "MongoDB");
query.put("type", "database");
System.out.println(con.findOne(query));
showDBCursor(con.find(query));
單字段or查詢(xún)
System.out.println("單字段or條件的使用,i2 or i>=18...");
BasicDBList values = new BasicDBList();
values.add(new BasicDBObject("i", new BasicDBObject("$gte", 18)));
values.add(new BasicDBObject("i", new BasicDBObject("$lt", 2)));
BasicDBObject query = new BasicDBObject();();
query.put("$or", values);
showDBCursor(con.find(query));
多字段or查詢(xún)
// "多字段or條件的使用,name:'MongoDB' or x:'203'..."
BasicDBList values = new BasicDBList(); ();
values.add(new BasicDBObject("name", "MongoDB"));
values.add(new BasicDBObject("x", 203));
BasicDBObject query = new BasicDBObject();();
query.put("$or", values);
showDBCursor(con.find(query));
$in 查詢(xún)
System.out.println("in條件的使用$in...");
BasicDBList values = new BasicDBList(); ();
for (int i = 1; i =10; i++) {
values.add(i);
}
BasicDBObject query = new BasicDBObject();();
query.put("i", new BasicDBObject("$in", values));
showDBCursor(con.find(query));
Order By 排序查詢(xún)
System.out.println("排序[1=asc,-1=desc]...");
showDBCursor(con.find(query).sort(new BasicDBObject("i", -1)));
分頁(yè)查詢(xún)
// "分頁(yè)查詢(xún)的使用,總數(shù)據(jù)量:"+con.find(query).count()
con.find(query).limit(1); // 只取第1條數(shù)據(jù)
con.find(query).skip(1).limit(1); // 從1開(kāi)始取1條數(shù)據(jù),下標(biāo)從0開(kāi)始
con.find(query).sort(new BasicDBObject("i", -1)).skip(0).limit(5); // DESC后取5條數(shù)據(jù)
//findAndRemove()方法,刪除查詢(xún)到的數(shù)據(jù),刪除后的結(jié)果集
con.findAndRemove(new BasicDBObject("i", 1));
showDBCursor(con.find(query));
con.findAndRemove(new BasicDBObject("i", new BasicDBObject("$in", values))); //【注意:多個(gè)數(shù)值無(wú)效】
showDBCursor(con.find(query));
(not) OR (not in)查詢(xún)
System.out.println("not,not in條件的使用$not");
BasicDBObject query = new BasicDBObject();();
query.put("i", new BasicDBObject("$not", new BasicDBObject("$in", values)));
showDBCursor(con.find(query));
Like模糊查詢(xún)
System.out.println("like查詢(xún)的使用...");
BasicDBObject query = new BasicDBObject();();
query.put("type", MonGoUtil.getLikeStr("a"));
showDBCursor(con.find(query));
根據(jù)字段類(lèi)型查詢(xún)
System.out.println("根據(jù)數(shù)據(jù)類(lèi)型查詢(xún),字符類(lèi)型...");
BasicDBObject query = new BasicDBObject();();
query.put("name", new BasicDBObject("$type", 2)); //字節(jié)
showDBCursor(con.find(query));
System.out.println("根據(jù)數(shù)據(jù)類(lèi)型查詢(xún),整型...");
BasicDBObject query = new BasicDBObject();();
query.put("i", new BasicDBObject("$type", 16));
showDBCursor(con.find(query));
返回查詢(xún)的部分字段
//"查詢(xún)數(shù)據(jù)的部分字段,1表示只返回本字段,0表示返回除此字段之外的字段"
con.find(new BasicDBObject("name", MonGoUtil.getLikeStr("b")), new BasicDBObject("name", 1));
5.java對(duì)collection的更新操作
//查詢(xún)id為300的記錄,將cust_Id的值更新為6533615,一定要注意大小寫(xiě),以及數(shù)據(jù)//類(lèi)型,返回值為int表示所影響的記錄條數(shù)
//可以用users.findOne(new BasicDBObject("_id",300));查看下,會(huì)發(fā)現(xiàn)這條記錄//只返回兩個(gè)字段了,分別為_(kāi)id,cust_Id,別的字段都刪除了。
users.update(new BasicDBObject("_id",300), new BasicDBObject ("cust_Id","6533615")).getN();
// 參數(shù)3表示數(shù)據(jù)庫(kù)不存在是否添加(默認(rèn)false),參數(shù)4表示是否多條修改(false只修改1條)
con.update(new BasicDBObject("name", "MongoDB"),
new BasicDBObject("$set", new BasicDBObject("type", "修改后的type"))).getN();
con.update(new BasicDBObject("name", "MongoDBs"),
new BasicDBObject("$set", new BasicDBObject("type", "修改后的type")), true, true).getN();
6.java對(duì)collection的刪除操作
/移除cust_Id為6533615的數(shù)據(jù)。注意 用remove方法不釋放磁盤(pán)空間,
//mongodb只在collection中做了標(biāo)志,沒(méi)有正在刪除。
users.remove(new BasicDBObject("cust_Id","6533615")).getN();
//移除id>=1的數(shù)據(jù)
users.remove(newBasicDBObject("_id",new BasicDBObject("$gte",1))).getN();
//移除整個(gè)collection,drop也不釋放磁盤(pán)空間
users.drop();
// 根據(jù)條件刪除文檔(數(shù)據(jù))
BasicDBList rls = new BasicDBList();
for (int i = 11; i = 20; i++) {
rls.add(i);
}
query.put("i", new BasicDBObject("$in", rls));
con.remove(query);
7.讀取mongodb中Binary Data類(lèi)型數(shù)據(jù)
Binary binary = (Binary) doc.get("Data");
byte[] data=binary.getData();
您可能感興趣的文章:- Java的idea連接mongodb數(shù)據(jù)庫(kù)的詳細(xì)教程
- Java單例模式下的MongoDB數(shù)據(jù)庫(kù)操作工具類(lèi)
- Java操作Mongodb數(shù)據(jù)庫(kù)實(shí)現(xiàn)數(shù)據(jù)的增刪查改功能示例
- 【MongoDB for Java】Java操作MongoDB數(shù)據(jù)庫(kù)
- java實(shí)現(xiàn)mongodb的數(shù)據(jù)庫(kù)連接池
- Java操作MongoDB數(shù)據(jù)庫(kù)示例分享
- Java操作MongoDB數(shù)據(jù)庫(kù)的示例代碼