java 操作mongodb_[转载]使用Java操作Mongodb

本文详述了如何使用Java进行MongoDB的基本操作,包括连接数据库、创建和查询文档,以及删除数据。通过示例代码展示了不同方式插入JSON数据,并提供了一步步的指导,从HelloWorld开始,直至数据库的CRUD操作。此外,还讨论了如何将JSON数据转换为DBObject,便于数据库交互。
摘要由CSDN通过智能技术生成

HelloWorld程序

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

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

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

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 packagecom.mkyong.core;2 importjava.net.UnknownHostException;3 importcom.mongodb.BasicDBObject;4 importcom.mongodb.DB;5 importcom.mongodb.DBCollection;6 importcom.mongodb.DBCursor;7 importcom.mongodb.Mongo;8 importcom.mongodb.MongoException;9

10 /**

11 * Java + MongoDB Hello world Example12 *13 */

14 public classApp {15 public static voidmain(String[] args) {16 try{17 //实例化Mongo对象,连接27017端口

18 Mongo mongo = new Mongo("localhost", 27017);19 //连接名为yourdb的数据库,假如数据库不存在的话,mongodb会自动建立

20 DB db = mongo.getDB("yourdb");21 //Get collection from MongoDB, database named "yourDB"22 //从Mongodb中获得名为yourColleection的数据集合,如果该数据集合不存在,Mongodb会为其新建立

23 DBCollection collection = db.getCollection("yourCollection");24 //使用BasicDBObject对象创建一个mongodb的document,并给予赋值。

25 BasicDBObject document = newBasicDBObject();26 document.put("id", 1001);27 document.put("msg", "hello world mongoDB in Java");28 //将新建立的document保存到collection中去

29 collection.insert(document);30 //创建要查询的document

31 BasicDBObject searchQuery = newBasicDBObject();32 searchQuery.put("id", 1001);33 //使用collection的find方法查找document

34 DBCursor cursor =collection.find(searchQuery);35 //循环输出结果

36 while(cursor.hasNext()) {37 System.out.println(cursor.next());38 }39 System.out.println("Done");40 } catch(UnknownHostException e) {41 e.printStackTrace();42 } catch(MongoException e) {43 e.printStackTrace();44 }45 }46 }

View Code

最后,输出的结果为:

{ "_id" : { "$oid" : "4dbe5596dceace565d229dc3"} ,                 "id" : 1001 , "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);  }

完成的一个例子如下:

package com.mkyong.core;import java.net.UnknownHostException;import java.util.Set;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.Mongo;import com.mongodb.MongoException;/*** Java : Get collection from MongoDB* */public class GetCollectionApp {public static void main(String[] args) {try {Mongo mongo = new Mongo("localhost", 27017);DB db = mongo.getDB("yourdb");Set 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

格式的数据,如下:

{  "database" : "mkyongDB",  "table" : "hosting",  "detail" :  {  records : 99,  index : "vps_index1",  active : "true"  }  }  }

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

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

BasicDBObject document = new BasicDBObject();document.put("database", "mkyongDB");document.put("table", "hosting");BasicDBObject documentDetail = new BasicDBObject();documentDetail.put("records", "99");documentDetail.put("index", "vps_index1");documentDetail.put("active", "true");document.put("detail", documentDetail);collection.insert(document);

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

BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()  .add("database", "mkyongDB")  .add("table", "hosting");  BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()  .add("records", "99")  .add("index", "vps_index1")  .add("active", "true");  documentBuilder.add("detail", documentBuilderDetail.get());  collection.insert(documentBuilder.get());

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

Map documentMap =new HashMap();  documentMap.put("database", "mkyongDB");  documentMap.put("table", "hosting");  Map documentMapDetail =new HashMap();  documentMapDetail.put("records", "99");  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中去。

完整的代码如下所示:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 packagecom.mkyong.core;2 importjava.net.UnknownHostException;3 importjava.util.HashMap;4 importjava.util.Map;5 importcom.mongodb.BasicDBObject;6 importcom.mongodb.BasicDBObjectBuilder;7 importcom.mongodb.DB;8 importcom.mongodb.DBCollection;9 importcom.mongodb.DBCursor;10 importcom.mongodb.DBObject;11 importcom.mongodb.Mongo;12 importcom.mongodb.MongoException;13 importcom.mongodb.util.JSON;14   /**

15 * Java MongoDB : Insert a Document16 *17   */

18 publicclass InsertDocumentApp {19 publicstaticvoid main(String[] args){20   try{21   Mongo mongo =new Mongo("localhost", 27017);22   DB db = mongo.getDB("yourdb");23   //get a single collection

24   DBCollection collection = db.getCollection("dummyColl");25   //BasicDBObject example

26   System.out.println("BasicDBObject example...");27   BasicDBObject document =newBasicDBObject();28   document.put("database", "mkyongDB");29   document.put("table", "hosting");30   BasicDBObject documentDetail =newBasicDBObject();31   documentDetail.put("records", "99");32   documentDetail.put("index", "vps_index1");33   documentDetail.put("active", "true");34   document.put("detail", documentDetail);35 collection.insert(document);36   DBCursor cursorDoc =collection.find();37   while(cursorDoc.hasNext()){38 System.out.println(cursorDoc.next());39 }40   collection.remove(newBasicDBObject());41   //BasicDBObjectBuilder example

42   System.out.println("BasicDBObjectBuilder example...");43   BasicDBObjectBuilder documentBuilder =BasicDBObjectBuilder.start()44   .add("database", "mkyongDB")45   .add("table", "hosting");46   BasicDBObjectBuilder documentBuilderDetail =BasicDBObjectBuilder.start()47   .add("records", "99")48   .add("index", "vps_index1")49   .add("active", "true");50   documentBuilder.add("detail", documentBuilderDetail.get());51 collection.insert(documentBuilder.get());52   DBCursor cursorDocBuilder =collection.find();53   while(cursorDocBuilder.hasNext()){54 System.out.println(cursorDocBuilder.next());55 }56   collection.remove(newBasicDBObject());57   //Map example

58   System.out.println("Map example...");59   Map documentMap =newHashMap();60   documentMap.put("database", "mkyongDB");61   documentMap.put("table", "hosting");62   Map documentMapDetail =newHashMap();63   documentMapDetail.put("records", "99");64   documentMapDetail.put("index", "vps_index1");65   documentMapDetail.put("active", "true");66   documentMap.put("detail", documentMapDetail);67   collection.insert(newBasicDBObject(documentMap));68   DBCursor cursorDocMap =collection.find();69   while(cursorDocMap.hasNext()){70 System.out.println(cursorDocMap.next());71 }72   collection.remove(newBasicDBObject());73   //JSON parse example

74   System.out.println("JSON parse example...");75   String json ="{'database' : 'mkyongDB','table' : 'hosting',"+

76   "'detail' : {'records' : 99, 'index' : 'vps_index1', 'active' : 'true'}}}";77   DBObject dbObject =(DBObject)JSON.parse(json);78 collection.insert(dbObject);79   DBCursor cursorDocJSON =collection.find();80   while(cursorDocJSON.hasNext()){81 System.out.println(cursorDocJSON.next());82 }83   collection.remove(newBasicDBObject());84   }catch(UnknownHostException e){85 e.printStackTrace();86   }catch(MongoException e){87 e.printStackTrace();88 }89 }90   }

View Code

更新Document

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

{"_id" : {"$oid" : "x"} , "hosting" : "hostA" , "type" : "vps" , "clients" : 1000}  {"_id" : {"$oid" : "x"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 100}  {"_id" : {"$oid" : "x"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900}

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

BasicDBObject newDocument =new BasicDBObject();  newDocument.put("hosting", "hostB");  newDocument.put("type", "shared host");  newDocument.put("clients", 111);  collection.update(new BasicDBObject().append("hosting", "hostB"), newDocument);

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

更新后的输出如下:

{"_id" : {"$oid" : "x"} , "hosting" : "hostA" , "type" : "vps" , "clients" : 1000}  {"_id" : {"$oid" : "x"} , "hosting" : "hostB" , "type" : "shared host" , "clients" : 111}  {"_id" : {"$oid" : "x"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900}

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

BasicDBObject newDocument =new BasicDBObject().append("$inc",  new BasicDBObject().append("clients", 99));  collection.update(new BasicDBObject().append("hosting", "hostB"), newDocument);

则输出如下:

{"_id" : {"$oid" : "x"} , "hosting" : "hostA" , "type" : "vps" , "clients" : 1000}  {"_id" : {"$oid" : "x"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 199}  {"_id" : {"$oid" : "x"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900}

接下来,讲解$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:

{"_id" : {"$oid" : "x"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 100}  {"_id" : {"$oid" : "x"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900}  {"_id" : {"$oid" : "x"} , "hosting" : "hostA" , "clients" : 1000 , "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,可以如下实现:

BasicDBObject updateQuery =new BasicDBObject().append("$set",  new BasicDBObject().append("clients", "888"));  collection.update(new BasicDBObject().append("type", "vps"), updateQuery, false, true);

输出如下:

{"_id" : {"$oid" : "x"} , "hosting" : "hostA" , "clients" : "888" , "type" : "vps"}  {"_id" : {"$oid" : "x"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 100}  {"_id" : {"$oid" : "x"} , "hosting" : "hostC" , "clients" : "888" , "type" : "vps"}

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

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 packagecom.liao;2   importjava.net.UnknownHostException;3   importcom.mongodb.BasicDBObject;4   importcom.mongodb.DB;5   importcom.mongodb.DBCollection;6   importcom.mongodb.DBCursor;7   importcom.mongodb.Mongo;8   importcom.mongodb.MongoException;9 publicclass UpdateDocumentApp {10 publicstaticvoid printAllDocuments(DBCollection collection){11   DBCursor cursor =collection.find();12   while(cursor.hasNext()) {13 System.out.println(cursor.next());14 }15 }16 publicstaticvoid removeAllDocuments(DBCollection collection){17   collection.remove(newBasicDBObject());18 }19 publicstaticvoid insertDummyDocuments(DBCollection collection){20   BasicDBObject document = newBasicDBObject();21   document.put("hosting", "hostA");22   document.put("type", "vps");23   document.put("clients", 1000);24   BasicDBObject document2 = newBasicDBObject();25   document2.put("hosting", "hostB");26   document2.put("type", "dedicated server");27   document2.put("clients", 100);28   BasicDBObject document3 = newBasicDBObject();29   document3.put("hosting", "hostC");30   document3.put("type", "vps");31   document3.put("clients", 900);32 collection.insert(document);33 collection.insert(document2);34 collection.insert(document3);35 }36 publicstaticvoid main(String[] args) {37   try{38   Mongo mongo = new Mongo("localhost", 27017);39   DB db = mongo.getDB("yourdb");40   DBCollection collection = db.getCollection("dummyColl");41   System.out.println("Testing 1...");42 insertDummyDocuments(collection);43   //find hosting = hostB, and update it with new document

44   BasicDBObject newDocument = newBasicDBObject();45   newDocument.put("hosting", "hostB");46   newDocument.put("type", "shared host");47   newDocument.put("clients", 111);48   collection.update(new BasicDBObject().append("hosting", "hostB"), newDocument);49 printAllDocuments(collection);50 removeAllDocuments(collection);51   System.out.println("Testing 2...");52 insertDummyDocuments(collection);53   BasicDBObject newDocument2 = new BasicDBObject().append("$inc",54   new BasicDBObject().append("clients", 99));55   collection.update(new BasicDBObject().append("hosting", "hostB"), newDocument2);56 printAllDocuments(collection);57 removeAllDocuments(collection);58   System.out.println("Testing 3...");59 insertDummyDocuments(collection);60   BasicDBObject newDocument3 = new BasicDBObject().append("$set",61   new BasicDBObject().append("type", "dedicated server"));62   collection.update(new BasicDBObject().append("hosting", "hostA"), newDocument3);63 printAllDocuments(collection);64 removeAllDocuments(collection);65   System.out.println("Testing 4...");66 insertDummyDocuments(collection);67   BasicDBObject updateQuery = new BasicDBObject().append("$set",68   new BasicDBObject().append("clients", "888"));69 collection.update(70   new BasicDBObject().append("type", "vps"), updateQuery, false, true);71 printAllDocuments(collection);72 removeAllDocuments(collection);73   System.out.println("Done");74   } catch(UnknownHostException e) {75 e.printStackTrace();76   } catch(MongoException e) {77 e.printStackTrace();78 }79 }80   }

View Code

查询Document

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

for(int i=1; i <=10; i++){  collection.insert(new BasicDBObject().append("number", i));  }

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

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

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

输出为:

{"_id" : {"$oid" : "4dc7f7b7bd0fb9a86c6c80bd"} , "number" : 1}

2)获得document的集合

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

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

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

{"_id" : {"$oid" : "4dc7f7b7bd0fb9a86c6c80bd"} , "number" : 1}  //..........中间部分省略,为2到9的输出{"_id" : {"$oid" : "4dc7f7b7bd0fb9a86c6c80c6"} , "number" : 10}

3) 获取指定的document

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

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

即输出:

{"_id" : {"$oid" : "4dc7f7b7bd0fb9a86c6c80c1"} , "number" : 5}

4) 使用in操作符号

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

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

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

{"_id" : {"$oid" : "4dc7f7b7bd0fb9a86c6c80c5"} , "number" : 9}  {"_id" : {"$oid" : "4dc7f7b7bd0fb9a86c6c80c6"} , "number" : 10}

5) 使用>,

在mongodb中,也可以使用比如>,5的document集合,则使用“$gt”即可,同理,小于关系则使用$lt,例子如下:

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

输出如下:

{"_id" : {"$oid" : "4dc7f7b7bd0fb9a86c6c80c2"} , "number" : 6}  {"_id" : {"$oid" : "4dc7f7b7bd0fb9a86c6c80c3"} , "number" : 7}  {"_id" : {"$oid" : "4dc7f7b7bd0fb9a86c6c80c4"} , "number" : 8}  {"_id" : {"$oid" : "4dc7f7b7bd0fb9a86c6c80c5"} , "number" : 9}  {"_id" : {"$oid" : "4dc7f7b7bd0fb9a86c6c80c6"} , "number" : 10}  也可以多个比较符号一起使用,比如要输出number>5和number<8的document,则如下:  BasicDBObject query =new BasicDBObject();  query.put("number", new BasicDBObject("$gt", 5).append("$lt", 8));  DBCursor cursor = collection.find(query);  while(cursor.hasNext()){  System.out.println(cursor.next());  }

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

BasicDBObject query5 =new BasicDBObject();  query5.put("number", new BasicDBObject("$ne", 8));  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,如下方法:

BasicDBObject document =new BasicDBObject();  document.put("number", 2);  collection.remove(document);

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

BasicDBObject document =new BasicDBObject();  document.put("number", 2);  document.put("number", 3);  collection.remove(document);

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

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

BasicDBObject query2 =new BasicDBObject();  List list =new ArrayList();  list.add(4);  list.add(5);  query2.put("number", new BasicDBObject("$in", list));  collection.remove(query2);

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

BasicDBObject query =new BasicDBObject();  query.put("number", new BasicDBObject("$gt", 9));  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格式的结果;

{  "_id" :  {  "$oid" : "4dc9511a14a7d017fee35746"  } ,  "chunkSize" : 262144 ,  "length" : 22672 ,  "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接口类型,要将它实例化为需要的对象。比如:

{  'name' : 'mkyong',  'age' : 30  }

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

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

完整的代码如下:

packagecom.mkyong.core;  importjava.net.UnknownHostException;  importcom.mongodb.DB;  importcom.mongodb.DBCollection;  importcom.mongodb.DBCursor;  importcom.mongodb.DBObject;  importcom.mongodb.Mongo;  importcom.mongodb.MongoException;  importcom.mongodb.util.JSON;  /*** Java MongoDB : Convert JSON data to DBObject  *  */  publicclass App {  publicstaticvoid main(String[] args){  try{  Mongo mongo =new Mongo("localhost", 27017);  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();  }  }  }

则输出为:

{"_id" : {"$oid" : "4dc9ebb5237f275c2fe4959f"} , "name" : "mkyong" , "age" : 30}

Done

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

小结:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值