Java與mongodb的連接
1. 連單臺mongodb
1
2
3
4
5
|
Mongo mg = new Mongo(); //默認連本機127.0.0.1 端口為27017 Mongo mg = new Mongo(ip); //可以指定ip 端口默認為27017 Mongo mg = new Mongo(ip,port); //也可以指定ip及端口 |
2. 連雙臺mongodb
1
2
3
4
5
6
7
8
9
|
//ip為主機ip地址,port為端口號,dataBaseName相當于數據庫名 DBAddress left = new DBAddress( "ip:port/dataBaseName" ); DBAddress right = new DBAddress( "ip:port/dataBaseName " ); //若一個mongodb出現問題,會自動連另外一臺 Mongo mongo = new Mongo(left, right); |
3. 連多臺mongodb
1
2
3
4
5
6
7
8
9
|
List<ServerAddress> mongoHostList = new ArrayList<ServerAddress>(); 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的數據庫名
1. 獲取mongodb的db(數據庫)
1
2
3
4
5
|
//dataBaseName相當于關系數據庫里的數據庫名,mongodb中若沒有該 //數據庫名也不會報錯,默認mongodb會建立這個數據庫名,為空。 DB db = mg.getDB(dataBaseName); |
注意:mongodb區分大小寫,程序中一定要注意
2.mongodb的db安全認證
1
2
3
4
5
6
7
8
9
10
11
12
13
|
//安全認證java代碼 返回true表示通過,false表示沒通過不能進行操作 db.authenticate( "userName" , "password" .toCharArray()); if (db.authenticate( "admin" , "123" .toCharArray())){ System.out.println( "連接mongodb成功..." ); } else { System.out.println( "連接mongodb失敗..." ); } |
Java對mongodb的collection進行crud操作
1.得到mongodb中的db的collection(表)
1
2
3
4
5
6
7
8
9
|
//參數tableName相當于關系數據庫里的表名, //若mongodb中沒有該tableName,默認會創建該tableName,為空 DBCollection users = db.getCollection(tableName); //列出庫的集合列表,相對于表對象 Set<String> colls = db.getCollectionNames(); for (String s : colls){ } // 獲取單個集合 DBCollection con = db.getCollection( "users" ); |
2.mongodb中的db的collection自增長主鍵
Mongodb中也像傳統的關系數據庫里表一樣,有主鍵(_id)概念,用來唯一標識他們。當用戶往collection中插入一條新記錄的時候,如果沒有指定_id屬性,那么mongodb會自動生成一個ObjectId類型的值,保存為_id的值。
_id的值可以為任何類型,除了數組,在實際應用中,鼓勵用戶自己定義_id值,但是要保證他的唯一性。
傳統的數據庫中,通常用一個遞增的序列來提供主鍵,在Mongodb中用ObjectId來代替,我們可以通過如下的方法來得到主鍵。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class Tools { /** * 實現mongodb主鍵自增長的功能 * @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對collection進行插入操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
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); //插入對象 //特殊添加 // 添加多個特殊數據(模式自由) 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對象 // 添加java對象,對象要序列化Serializable接口 UserInfo userinfo = new UserInfo( "用戶甲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())); List<UserInfo> list = new ArrayList<UserInfo>(); 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對collection的查詢操作
1
2
3
4
5
6
7
8
9
10
11
12
13
|
/** 輸出獲取到的文檔 **/ public static void showDBCursor(DBCursor cur){ while (cur.hasNext()){ System.out.println(cur.next()); } System.out.println(); } |
高級查詢
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
//查詢_id為30000 返回cust_Id的值 ,mongodb查詢都會返回主鍵的值 System.out.println(users.findOne( new BasicDBObject( "_id" , 30000 ), new BasicDBObject( "cust_Id" , true ))); findAndRemove() 查詢_id= 30000 的數據,并且刪除 users.findAndRemove( new BasicDBObject( "_id" , 30000 )); findAndModify介紹 users.findAndModify( new BasicDBObject( "_id" , 28 ), //查詢_id=28的數據 new BasicDBObject( "cust_Id" , true ), //查詢cust_Id屬性 new BasicDBObject( "notice_Id" , true ), //按照notice_Id排序 false , //查詢到的記錄是否刪除,true表示刪除 new BasicDBObject( "province_Id" , "100" ), //將province_id的值改為100 true , //是否返回新記錄 true返回,false不返回 true //如果沒有查詢到該數據是否插collection true入庫,false不入 )); |
查詢所有數據
1
2
3
4
5
6
7
|
//列出所有文檔 BasicDBObject query = new BasicDBObject(); System.out.println( "列出" + con.getName() + "集合(表)的所有文檔..." ); showDBCursor(con.find()); |
查詢JAVA對象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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( "用戶對象_json:" + JSONArray.fromObject(users)); |
單一條件查詢(數字)
1
2
3
4
5
|
BasicDBObject query = new BasicDBObject(); query.put( "i" , 11 ); showDBCursor(con.find(query)); |
單一條件查詢(字符串)
1
2
3
4
5
|
BasicDBObject query = new BasicDBObject(); query.put( "name" , "MongoDB" ); showDBCursor(con.find(query)); |
$ne非等于查詢
1
2
3
4
5
|
BasicDBObject query = new BasicDBObject(); query.put( "name" , new BasicDBObject( "$ne" , "MongoDB" )); showDBCursor(con.find(query)); |
根據列名查詢
1
2
3
4
5
6
7
|
System.out.println( "查詢有'type'字段的數據..." ); // false表示沒有 BasicDBObject query = new BasicDBObject(); query.put( "type" , new BasicDBObject( "$exists" , true )); // false showDBCursor(con.find(query)); |
單字段and查詢
1
2
3
4
5
6
7
|
System.out.println( "單字段and條件的使用,i>=2 and i<5 ,i:[2,5)..." ); BasicDBObject query = new BasicDBObject(); query.put( "i" , new BasicDBObject( "$gte" , 2 ).append( "$lt" , 5 )); showDBCursor(con.find(query)); |
多字段and查詢
1
2
3
4
5
6
7
8
9
|
BasicDBObject query = new BasicDBObject();(); query.put( "name" , "MongoDB" ); query.put( "type" , "database" ); System.out.println(con.findOne(query)); showDBCursor(con.find(query)); |
單字段or查詢
1
2
3
4
5
6
7
8
9
10
11
12
13
|
System.out.println( "單字段or條件的使用,i<2 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查詢
1
2
3
4
5
6
7
8
9
10
11
12
13
|
// "多字段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 查詢
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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 排序查詢
1
2
3
|
System.out.println( "排序[1=asc,-1=desc]..." ); showDBCursor(con.find(query).sort( new BasicDBObject( "i" , - 1 ))); |
分頁查詢
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
// "分頁查詢的使用,總數據量:"+con.find(query).count() con.find(query).limit( 1 ); // 只取第1條數據 con.find(query).skip( 1 ).limit( 1 ); // 從1開始取1條數據,下標從0開始 con.find(query).sort( new BasicDBObject( "i" , - 1 )).skip( 0 ).limit( 5 ); // DESC后取5條數據 //findAndRemove()方法,刪除查詢到的數據,刪除后的結果集 con.findAndRemove( new BasicDBObject( "i" , 1 )); showDBCursor(con.find(query)); con.findAndRemove( new BasicDBObject( "i" , new BasicDBObject( "$in" , values))); //【注意:多個數值無效】 showDBCursor(con.find(query)); |
(not) OR (not in)查詢
1
2
3
4
5
6
7
|
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模糊查詢
1
2
3
4
5
6
7
|
System.out.println( "like查詢的使用..." ); BasicDBObject query = new BasicDBObject();(); query.put( "type" , MonGoUtil.getLikeStr( "a" )); showDBCursor(con.find(query)); |
根據字段類型查詢
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
System.out.println( "根據數據類型查詢,字符類型..." ); BasicDBObject query = new BasicDBObject();(); query.put( "name" , new BasicDBObject( "$type" , 2 )); //字節 showDBCursor(con.find(query)); System.out.println( "根據數據類型查詢,整型..." ); BasicDBObject query = new BasicDBObject();(); query.put( "i" , new BasicDBObject( "$type" , 16 )); showDBCursor(con.find(query)); |
返回查詢的部分字段
1
2
3
|
//"查詢數據的部分字段,1表示只返回本字段,0表示返回除此字段之外的字段" con.find( new BasicDBObject( "name" , MonGoUtil.getLikeStr( "b" )), new BasicDBObject( "name" , 1 )); |
5.java對collection的更新操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
//查詢id為300的記錄,將cust_Id的值更新為6533615,一定要注意大小寫,以及數據//類型,返回值為int表示所影響的記錄條數 //可以用users.findOne(new BasicDBObject("_id",300));查看下,會發現這條記錄//只返回兩個字段了,分別為_id,cust_Id,別的字段都刪除了。 users.update( new BasicDBObject( "_id" , 300 ), new BasicDBObject ( "cust_Id" , "6533615" )).getN(); // 參數3表示數據庫不存在是否添加(默認false),參數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對collection的刪除操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
/移除cust_Id為 6533615 的數據。注意 用remove方法不釋放磁盤空間, //mongodb只在collection中做了標志,沒有正在刪除。 users.remove( new BasicDBObject( "cust_Id" , "6533615" )).getN(); //移除id>=1的數據 users.remove(newBasicDBObject( "_id" , new BasicDBObject( "$gte" , 1 ))).getN(); //移除整個collection,drop也不釋放磁盤空間 users.drop(); // 根據條件刪除文檔(數據) 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類型數據
1
2
3
|
Binary binary = (Binary) doc.get( "Data" ); byte [] data=binary.getData(); |
原文鏈接:https://www.jianshu.com/p/31daf8d67c11