好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java操作MongoDB数据库方法详解

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://HdhCmsTestjianshu测试数据/p/31daf8d67c11

查看更多关于Java操作MongoDB数据库方法详解的详细内容...

  阅读:32次