【IT168 专稿】在上一篇文章中,我们学习了Mongodb的安装和初步使用,在本文中,将学习如何使用Java去编程实现对Mongodb的操作。

  HelloWorld程序

  学习任何程序的第一步,都是编写HelloWorld程序,我们也不例外,看下如何通过Java编写一个HelloWorld的程序。

  首先,要通过Java操作Mongodb,必须先下载Mongodb的Java驱动程序,可以在这里下载

  新建立一个Java工程,将下载的驱动程序放在库文件路径下,程序代码如下:

);             // 使用collection的find方法查找document            DBCursor cursor = collection.find(searchQuery);             //循环输出结果            while (cursor.hasNext()) {             System.out.println(cursor.next());             }             System.out.println("Done");          } catch (UnknownHostException e) {             e.printStackTrace();         } catch (MongoException e) {             e.printStackTrace();         }     } }

  最后,输出的结果为:

 , "msg" : "hello world mongoDB in Java"} Done

  在上面的例子中,演示了使用Java对Mongodb操作的重要方法和步骤,首先通过创建Mongodb对象,传入构造函数的参数是Mongodb的数据库所在地址和端口,然后使用

  getDB方法获得要连接的数据库名,使用getCollection获得数据集合的名,然后通过新建立BasicDBObject对象去建立document,最后通过collection的insert方法,将建立的document保存到数据库中去。而collection的find方法,则是用来在数据库中查找document。

  从Mongodb中获得collection数据集

  在Mongodb中,可以通过如下方法获得数据库中的collection:

  DBCollection collection = db.getCollection("yourCollection");

  如果你不知道collection的名称,可以使用db.getCollectionNames()获得集合,然后再遍历,如下:

  DB db = mongo.getDB("yourdb");   Set collections = db.getCollectionNames();   for(String collectionName : collections){   System.out.println(collectionName);   }

  完成的一个例子如下:

); DB db = mongo.getDB("yourdb"); Set<String> collections = db.getCollectionNames(); for (String collectionName : collections) { System.out.println(collectionName); } DBCollection collection = db.getCollection("yourCollection"); System.out.println(collection.toString()); System.out.println("Done");
} catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } } }

  Mongodb中如何插入数据

  下面,讲解下如何使用4种方式,将JSON数据插入到Mongodb中去。首先我们准备JSON

  格式的数据,如下:

,   index : "vps_index1",   active : "true"   }   }   }

  我们希望用不同的方式,通过JAVA代码向Mongodb插入以上格式的JSON数据

  第一种方法,是使用BasicDBObject,方法如下代码所示:

"); documentDetail.put("index", "vps_index1"); documentDetail.put("active", "true"); document.put("detail", documentDetail); collection.insert(document);

  第二种方法是使用BasicDBObjectBuilder对象,如下代码所示:

")   .add("index", "vps_index1")   .add("active", "true");   documentBuilder.add("detail", documentBuilderDetail.get());   collection.insert(documentBuilder.get());

  第三种方法是使用Map对象,代码如下:

");   documentMapDetail.put("index", "vps_index1");   documentMapDetail.put("active", "true");   documentMap.put("detail", documentMapDetail);   collection.insert(new BasicDBObject(documentMap));

  第四种方法,也就是最简单的,即直接插入JSON格式数据

  String json ="{'database' : 'mkyongDB','table' : 'hosting',"+   "'detail' : {'records' : 99, 'index' : 'vps_index1', 'active' : 'true'}}}";   DBObject dbObject =(DBObject)JSON.parse(json);   collection.insert(dbObject);

  这里使用了JSON的parse方法,将解析后的JSON字符串转变为DBObject对象后再直接插入到collection中去。

  完整的代码如下所示:

");   documentMapDetail.put("index", "vps_index1");   documentMapDetail.put("active", "true");   documentMap.put("detail", documentMapDetail);   collection.insert(new BasicDBObject(documentMap));   DBCursor cursorDocMap = collection.find();   while(cursorDocMap.hasNext()){   System.out.println(cursorDocMap.next());   }   collection.remove(new BasicDBObject());   // JSON parse example  System.out.println("JSON parse example...");   String json ="{'database' : 'mkyongDB','table' : 'hosting',"+   "'detail' : {'records' : 99, 'index' : 'vps_index1', 'active' : 'true'}}}";   DBObject dbObject =(DBObject)JSON.parse(json);   collection.insert(dbObject);   DBCursor cursorDocJSON = collection.find();   while(cursorDocJSON.hasNext()){   System.out.println(cursorDocJSON.next());   }   collection.remove(new BasicDBObject());   }catch(UnknownHostException e){   e.printStackTrace();   }catch(MongoException e){   e.printStackTrace();   }   }   }

  更新Document

  假设如下的JSON格式的数据已经保存到Mongodb中去了,现在要更新相关的数据。

}

  假设现在要将hosting中值为hostB的进行更新,则可以使用如下的方法:

);   collection.update(new BasicDBObject().append("hosting", "hostB"), newDocument);

  可以看到,这里依然使用了BasicDBObject对象,并为其赋值了新的值后,然后使用collection的update方法,即可更新该对象。

  更新后的输出如下:

}

  另外,还可以使用mongodb中的$inc修饰符号去对某个值进行更新,比如,要将hosting值为hostB的document的clients的值得更新为199(即100+99=199),可以这样:

));   collection.update(new BasicDBObject().append("hosting", "hostB"), newDocument);

  则输出如下:

}

  接下来,讲解$set修饰符的使用。比如要把hosting中值为hostA的document中的

  type的值进行修改,则可以如下实现:

  BasicDBObject newDocument3 =new BasicDBObject().append("$set",   new BasicDBObject().append("type", "dedicated server"));   collection.update(new BasicDBObject().append("hosting", "hostA"), newDocument3);

  则输出如下,把type的值从vps改为dedicated server:

 , "type" : "dedicated server"}

  要注意的是,如果不使用$set的修饰符,而只是如下代码:

  BasicDBObject newDocument3 =new BasicDBObject().append("type", "dedicated server");   collection.update(new BasicDBObject().append("hosting", "hostA"), newDocument3);

  则会将所有的三个document的type类型都改为dedicated server了,因此要使用$set以更新特定的document的特定的值。

  如果要更新多个document中相同的值,可以使用$multi,比如,要把所有vps为type的document,将它们的clients的值更新为888,可以如下实现:

"));   collection.update(new BasicDBObject().append("type", "vps"), updateQuery, false, true);

  输出如下:

" , "type" : "vps"}

  最后,还是给出更新document的完整例子:

"));   collection.update(   new BasicDBObject().append("type", "vps"), updateQuery, false, true);   printAllDocuments(collection);   removeAllDocuments(collection);   System.out.println("Done");   } catch (UnknownHostException e) {   e.printStackTrace();   } catch (MongoException e) {   e.printStackTrace();   }   }   }

  查询Document

  下面学习如何查询document,先用下面的代码往数据库中插入1-10数字:

; i++){   collection.insert(new BasicDBObject().append("number", i));
  }

  接下来,看下如下的例子:

  1) 获得数据库中的第一个document:

  DBObject doc = collection.findOne();   System.out.println(dbObject);

  输出为:

}

  2)获得document的集合

  DBCursor cursor = collection.find();   while(cursor.hasNext()){   System.out.println(cursor.next());   }

  这里,使用collection.find()方法,获得当前数据库中所有的documents对象集合

  然后通过对DBCursor对象集合的遍历,即可输出当前所有documents。输出如下:

}

  3) 获取指定的document

  比如要获得number=5的document对象内容,可以使用collection的find方法即可,如下:

);   DBCursor cursor = collection.find(query);   while(cursor.hasNext()){   System.out.println(cursor.next());   }

  即输出:

}

  4) 使用in操作符号

  在mongodb中,也可以使用in操作符,比如要获得number=9和number=10的document对象,可以如下操作:

);   query.put("number", new BasicDBObject("$in", list));   DBCursor cursor = collection.find(query);   while(cursor.hasNext()){   System.out.println(cursor.next());   }

  这里使用了一个List,并将list传入到BasicDBObject的构造函数中,并使用了in操作符号,输出如下:

}

  5) 使用>,<等比较符号

  在mongodb中,也可以使用比如>,<等数量比较符号,比如要输出number>5的document集合,则使用“$gt”即可,同理,小于关系则使用$lt,例子如下:

));   DBCursor cursor = collection.find(query);   while(cursor.hasNext()){   System.out.println(cursor.next());   }

  输出如下:

));   DBCursor cursor = collection.find(query);   while(cursor.hasNext()){   System.out.println(cursor.next());   }

  同样,如果是不等于的关系的话,可以使用$ne操作符,如下:

));   DBCursor cursor6 = collection.find(query5);   while(cursor6.hasNext()){   System.out.println(cursor6.next());   }

  以上输出number=8之外的所有document。

  删除document

  下面我们学习如何删除document,依然以上面的已插入的1-10的documents集合为例说明:

  1) 删除第一个document

  DBObject doc = collection.findOne();   collection.remove(doc);

  2) 删除指定的document

  比如删除number=2的document,如下方法:

);   collection.remove(document);

  要注意的是,如下的方法将只会删除number=3的document。

);   collection.remove(document);

  3) 使用in 操作符号指定删除document

  下面的例子将同时删除number=4和number=5的document,使用的是in操作符

);   query2.put("number", new BasicDBObject("$in", list));   collection.remove(query2);

  4) 使用“$gt”删除大于某个值的document

));   collection.remove(query);

  以上会删除number=10的document。

  5) 删除所有的document

  DBCursor cursor = collection.find();   while(cursor.hasNext()){   collection.remove(cursor.next());   }

  保存图片到Mongodb

  下面将讲解如何使用Java MongoDB GridFS API去保存图片等二进制文件到Monodb,关于Java MongoDB GridFS API的详细论述,请参考http://www.mongodb.org/display/DOCS/GridFS+Specification

  1)保存图片

  代码段如下:

  String newFileName ="mkyong-java-image";   File imageFile =newFile("c:\\JavaWebHosting.png");   GridFS gfsPhoto =new GridFS(db, "photo");   GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);   gfsFile.setFilename(newFileName);   gfsFile.save();

  这里,将c盘下的JavaWebHosting.png保存到mongodb中去,并命名为mkyong-java-image。

  2) 读取图片信息

  代码段如下

  String newFileName ="mkyong-java-image";   GridFS gfsPhoto =new GridFS(db, "photo");   GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);   System.out.println(imageForOutput);

  将会输出JSON格式的结果;

 ,   "md5" : "1462a6cfa27669af1d8d21c2d7dd1f8b" ,   "filename" : "mkyong-java-image" ,   "contentType" : null ,   "uploadDate" :   {   "$date" : "2011-05-10T14:52:10Z"   } ,   "aliases" : null   }

  可以看到,输出的是文件的属性相关信息。

  3) 输出已保存的所有图片

  下面代码段,输出所有保存在photo命名空间下的图片信息:

  GridFS gfsPhoto =new GridFS(db, "photo");   DBCursor cursor = gfsPhoto.getFileList();   while(cursor.hasNext()){   System.out.println(cursor.next());   }

  4) 从数据库中读取一张图片并另存

  下面的代码段,从数据库中读取一张图片并另存为另外一张图片到磁盘中

  String newFileName ="mkyong-java-image";   GridFS gfsPhoto =new GridFS(db, "photo");   GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);   imageForOutput.writeTo("c:\\JavaWebHostingNew.png");

  5) 删除图片

  String newFileName ="mkyong-java-image";   GridFS gfsPhoto =new GridFS(db, "photo");   gfsPhoto.remove(gfsPhoto.findOne(newFileName));

  如何将JSON数据格式转化为DBObject格式

  在mongodb中,可以使用com.mongodb.util.JSON类,将JSON格式的字符串转变为DBObject对象。MongoDB for JAVA驱动中提供了用于向数据库中存储普通对象的接口DBObject,当一个文档从MongoDB中取出时,它会自动把文档转换成DBObject接口类型,要将它实例化为需要的对象。比如:

  }

  这样的JSON格式字符串,转换方法为:

  DBObject dbObject =(DBObject) JSON.parse("{'name':'mkyong', 'age':30}");

  完整的代码如下:

);   DB db = mongo.getDB("yourdb");   DBCollection collection = db.getCollection("dummyColl");   DBObject dbObject =(DBObject) JSON   .parse("{'name':'mkyong', 'age':30}");   collection.insert(dbObject);   DBCursor cursorDoc = collection.find();   while(cursorDoc.hasNext()){   System.out.println(cursorDoc.next());   }   System.out.println("Done");   }catch(UnknownHostException e){   e.printStackTrace();   }catch(MongoException e){   e.printStackTrace();   }   }   }

  则输出为:

}
  Done

  可以看到,将JSON格式的数据类型直接转换为mongodb中的文档类型并输出。

  小结:

  本文学习了如何使用Mongodb for JAVA驱动,对mongodb进行日常的数据库操作,比如增加,删除和修改,下一篇教程中,将指导学习Spring对mongodb的操作

Mongodb快速入门之使用Java操作Mongodb的更多相关文章

  1. Mongodb入门并使用java操作Mongodb

    转载请注意出处:http://blog.csdn.net/zcm101 最近在学习NoSql,先从Mongodb入手,把最近学习的总结下. Mongodb下载安装 Mongodb的下载安装就不详细说了 ...

  2. JAVA操作MongoDB数据库

    1. 首先,下载MongoDB对Java支持的驱动包 驱动包下载地址:https://github.com/mongodb/mongo-java-driver/downloads 2.Java操作Mo ...

  3. 前端开发小白必学技能—非关系数据库又像关系数据库的MongoDB快速入门命令(2)

    今天给大家道个歉,没有及时更新MongoDB快速入门的下篇,最近有点小忙,在此向博友们致歉.下面我将简单地说一下mongdb的一些基本命令以及我们日常开发过程中的一些问题.mongodb可以为我们提供 ...

  4. MongoDb 快速入门教程

    文章首发于[博客园-陈树义],点击跳转到原文MongoDb 快速入门教程. MongoDb 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的. 它是可扩展的 ...

  5. MongoDB快速入门指南与docker-compose快体验

    MongoDB快速入门指南与docker-compose快体验 MongoDB相对于RDBMS的优势 模式少 -MongoDB是一个文档数据库,其中一个集合包含不同的文档.一个文档之间的字段数,内容和 ...

  6. 【MongoDB for Java】Java操作MongoDB

    上一篇文章: http://www.cnblogs.com/hoojo/archive/2011/06/01/2066426.html介绍到了在MongoDB的控制台完成MongoDB的数据操作,通过 ...

  7. [转]MongoDB for Java】Java操作MongoDB

    原文地址: MongoDB for Java]Java操作MongoDB 开发环境: System:Windows IDE:eclipse.MyEclipse 8 Database:mongoDB 开 ...

  8. Java操作MongoDB

    上一篇文章: http://www.cnblogs.com/hoojo/archive/2011/06/01/2066426.html 介绍到了在MongoDB的控制台完成MongoDB的数据操作,通 ...

  9. 浅谈如何用Java操作MongoDB

    NoSQL数据库因其可扩展性使其变得越来越流行,利用NoSQL数据库可以给你带来更多的好处,MongoDB是一个用C++编写的可度可扩展性的开源NoSQL数据库.本文主要讲述如何使用Java操作Mon ...

随机推荐

  1. Jmeter软件测试1--webservice测试

    写在前言 程序猿一枚,原本就是负责安安静静的撸代码,后来公司让兼任下测试的工作,还得照顾下面的几个测试兄弟,无奈本人毫无软件测试理论知识,下面的测试兄弟也是初级水平,又面临公司要求做webservic ...

  2. Spring+AOP+Log4j 用注解的方式记录指定某个方法的日志

    一.spring aop execution表达式说明 在使用spring框架配置AOP的时候,不管是通过XML配置文件还是注解的方式都需要定义pointcut"切入点" 例如定义 ...

  3. 深度探索va_start、va_arg、va_end

    采用C语言编程的时候,函数中形式参数的数目通常是确定的,在调用时要依次给出与形式参数对应的所有实际参数.但在某些情况下希望函数的参数个数可以根据需要确定.典型的例子有大家熟悉的函数printf().s ...

  4. 读书笔记之 - javascript 设计模式 - 组合模式

    组合模式是一种专为创建Web上的动态用户界面而量身定制的模式,使用这种模式,可以用一条命令在对各对象上激发复杂的或递归的行为. 在组合对象的层次体系中有俩种类型对象:叶对象和组合对象.这是一个递归定义 ...

  5. busybox下mount nfs的命令

    busybox下mount nfs的命令 mount -f nfs -o nolock 10.130.30.2:/nfs/nuc970/rootfs /mnt/test

  6. 学习笔记--【转】Parameter与Attribute的区别&servletContext与ServletConfig区别

    原文链接http://blog.csdn.net/saygoodbyetoyou/article/details/9006001   Parameter与Attribute的区别   request. ...

  7. [开源]jquery-ajax-cache:快速优化页面ajax请求,使用localStorage缓存请求

    项目:jquery-ajax-cache 地址:https://github.com/WQTeam/jquery-ajax-cache     最近在项目中用到了本地缓存localStorage做数据 ...

  8. 分页插件jquery.simplePagination.js使用

    利用ecshop后台,利用插件更改分页显示样式遇到的问题,由于是利用Ajax获取数据进行页面数据更新?所以出现了以下情况: 初始化页面前 : 分页更新后: 点击后出现了分页插件内容消失, 原因:分页一 ...

  9. 通过Java代码浅谈HTTP协议

    最近刚看了http协议,想写点东西加深一下理解,如果哪儿写错了,请指正. 1 介绍 HTTP是Hyper Text Transfer Protocol(超文本传输协议)的缩写.它的发展是万维网协会(W ...

  10. Python3 time()

    在<Python基础教程(第二版)>一书中, if time % 60 == 0 : print 'on the hour! '在3.3.2版本中显示错误.于是自己查了一下帮助文档,也在网 ...