上一篇文章: http://blog.csdn.net/wangpeng047/article/details/7705588介绍到了在MongoDB的控制台完成MongoDB的数据操作,通过前一篇文章我们对MongoDB有了全面的认识和理解。现在我们就用Java来操作MongoDB的数据。
?
开发环境:
System:Windows
IDE:eclipse、MyEclipse 8
Database:mongoDB
开发依赖库:
JavaEE5、mongo-2.5.3.jar、junit-4.8.2.jar
Email:hoojo_@126.com
Blog:http://blog.csdn.net/IBM_hoojo
http://hoojo.cnblogs.com/
一、准备工作
1、 首先,下载mongoDB对Java支持的驱动包
驱动包下载地址:https://github.com/mongodb/mongo-java-driver/downloads
mongoDB对Java的相关支持、技术:http://www.mongodb.org/display/DOCS/Java+Language+Center
驱动源码下载:https://download.github.com/mongodb-mongo-java-driver-r2.6.1-7-g6037357.zip
在线查看源码:https://github.com/mongodb/mongo-java-driver
2、 下面建立一个JavaProject工程,导入下载下来的驱动包。即可在Java中使用mongoDB,目录如下:
二、Java操作MongoDB示例
在本示例之前你需要启动mongod.exe的服务,启动后,下面的程序才能顺利执行;
1、 建立SimpleTest.java,完成简单的mongoDB数据库操作
[java] view plaincopy
?
class="dp-j">
- Mongo?mongo?=?new?Mongo();???
这样就创建了一个MongoDB的数据库连接对象,它默认连接到当前机器的localhost地址,端口是27017。
[java] view plaincopy
?
- DB?db?=?mongo.getDB(“test”);???
这样就获得了一个test的数据库,如果mongoDB中没有创建这个数据库也是可以正常运行的。如果你读过上一篇文章就知道,mongoDB可以在没有创建这个数据库的情况下,完成数据的添加操作。当添加的时候,没有这个库,mongoDB会自动创建当前数据库。
得到了db,下一步我们要获取一个“聚集集合DBCollection”,通过db对象的getCollection方法来完成。
[java] view plaincopy
?
- DBCollection?users?=?db.getCollection("users");???
这样就获得了一个DBCollection,它相当于我们数据库的“表”。
查询所有数据
[java] view plaincopy
?
- DBCursor?cur?=?users.find();??
-
while?(cur.hasNext())?{??
- ???System.out.println(cur.next());??
- }???
完整源码
[java] view plaincopy
?
-
package?com.hoo.test;??
- ???
-
import?java.net.UnknownHostException;??
-
import?com.mongodb.DB;??
-
import?com.mongodb.DBCollection;??
-
import?com.mongodb.DBCursor;??
-
import?com.mongodb.Mongo;??
-
import?com.mongodb.MongoException;??
-
import?com.mongodb.util.JSON;??
- ??
-
public?class?SimpleTest?{??
- ???
- ????public?static?void?main(String[]?args)?throws?UnknownHostException,?MongoException?{??
- ????????Mongo?mg?=?new?Mongo();??
- ??????????
- ????????for?(String?name?:?mg.getDatabaseNames())?{??
- ????????????System.out.println("dbName:?"?+?name);??
- ????????}??
- ??????????
- ????????DB?db?=?mg.getDB("test");??
- ??????????
- ????????for?(String?name?:?db.getCollectionNames())?{??
- ????????????System.out.println("collectionName:?"?+?name);??
- ????????}??
- ??????????
- ????????DBCollection?users?=?db.getCollection("users");??
- ??????????
- ??????????
- ????????DBCursor?cur?=?users.find();??
- ????????while?(cur.hasNext())?{??
- ????????????System.out.println(cur.next());??
- ????????}??
- ????????System.out.println(cur.count());??
- ????????System.out.println(cur.getCursorId());??
- ????????System.out.println(JSON.serialize(cur));??
- ????}??
- }??
2、 完成CRUD操作,首先建立一个MongoDB4CRUDTest.java,基本测试代码如下:
[java] view plaincopy
?
-
package?com.hoo.test;??
- ???
-
import?java.net.UnknownHostException;??
-
import?java.util.ArrayList;??
-
import?java.util.List;??
-
import?org.bson.types.ObjectId;??
-
import?org.junit.After;??
-
import?org.junit.Before;??
-
import?org.junit.Test;??
-
import?com.mongodb.BasicDBObject;??
-
import?com.mongodb.Bytes;??
-
import?com.mongodb.DB;??
-
import?com.mongodb.DBCollection;??
-
import?com.mongodb.DBCursor;??
-
import?com.mongodb.DBObject;??
-
import?com.mongodb.Mongo;??
-
import?com.mongodb.MongoException;??
-
import?com.mongodb.QueryOperators;??
-
import?com.mongodb.util.JSON;??
- ??
-
public?class?MongoDB4CRUDTest?{??
- ??????
- ????private?Mongo?mg?=?null;??
- ????private?DB?db;??
- ????private?DBCollection?users;??
- ??????
- ????@Before??
- ????public?void?init()?{??
- ????????try?{??
- ????????????mg?=?new?Mongo();??
- ??????????????
- ????????}?catch?(UnknownHostException?e)?{??
- ????????????e.printStackTrace();??
- ????????}?catch?(MongoException?e)?{??
- ????????????e.printStackTrace();??
- ????????}??
- ??????????
- ????????db?=?mg.getDB("temp");??
- ??????????
- ????????users?=?db.getCollection("users");??
- ????}??
- ??????
- ????@After??
- ????public?void?destory()?{??
- ????????if?(mg?!=?null)??
- ????????????mg.close();??
- ????????mg?=?null;??
- ????????db?=?null;??
- ????????users?=?null;??
- ????????System.gc();??
- ????}??
- ??????
- ????public?void?print(Object?o)?{??
- ????????System.out.println(o);??
- ????}??
- }??
3、 添加操作
在添加操作之前,我们需要写个查询方法,来查询所有的数据。代码如下:
[java] view plaincopy
?
-
?
-
?
-
??
-
private?void?queryAll()?{??
- ????print("查询users的所有数据:");??
- ??????
- ????DBCursor?cur?=?users.find();??
- ????while?(cur.hasNext())?{??
- ????????print(cur.next());??
- ????}??
- }??
- ???
-
@Test??
-
public?void?add()?{??
- ??????
- ????queryAll();??
- ????print("count:?"?+?users.count());??
- ??????
- ????DBObject?user?=?new?BasicDBObject();??
- ????user.put("name",?"hoojo");??
- ????user.put("age",?24);??
- ??????
- ??????
- ??????
- ??????
- ????user.put("sex",?"男");??
- ????print(users.save(user).getN());??
- ??????
- ??????
- ????print(users.insert(user,?new?BasicDBObject("name",?"tom")).getN());??
- ??????
- ??????
- ????List<DBObject>?list?=?new?ArrayList<DBObject>();??
- ????list.add(user);??
- ????DBObject?user2?=?new?BasicDBObject("name",?"lucy");??
- ????user.put("age",?22);??
- ????list.add(user2);??
- ??????
- ????print(users.insert(list).getN());??
- ??????
- ??????
- ????print("count:?"?+?users.count());??
- ????queryAll();??
- }??
?4、 删除数据
[java] view plaincopy
?
-
@Test??
-
public?void?remove()?{??
- ????queryAll();??
- ????print("删除id?=?4de73f7acd812d61b4626a77:"?+?users.remove(new?BasicDBObject("_id",?new?ObjectId("4de73f7acd812d61b4626a77"))).getN());??
- ????print("remove?age?>=?24:?"?+?users.remove(new?BasicDBObject("age",?new?BasicDBObject("$gte",?24))).getN());??
- }??
5、 修改数据
[java] view plaincopy
?
-
@Test??
-
public?void?modify()?{??
- ????print("修改:"?+?users.update(new?BasicDBObject("_id",?new?ObjectId("4dde25d06be7c53ffbd70906")),?new?BasicDBObject("age",?99)).getN());??
- ????print("修改:"?+?users.update(??
- ????????????new?BasicDBObject("_id",?new?ObjectId("4dde2b06feb038463ff09042")),???
- ????????????new?BasicDBObject("age",?121),??
- ????????????true,??
- ????????????false??
- ????????????).getN());??
- ????print("修改:"?+?users.update(??
- ????????????new?BasicDBObject("name",?"haha"),???
- ????????????new?BasicDBObject("name",?"dingding"),??
- ????????????true,??
- ????????????true??
- ????????????).getN());??
- ??????
- ??????
- ??????
- }??
6、 查询数据
[java] view plaincopy
?
-
@Test??
-
public?void?query()?{??
- ??????
- ??????
- ??????
- ??????
- ????print("find?id?=?4de73f7acd812d61b4626a77:?"?+?users.find(new?BasicDBObject("_id",?new?ObjectId("4de73f7acd812d61b4626a77"))).toArray());??
- ??????
- ??????
- ????print("find?age?=?24:?"?+?users.find(new?BasicDBObject("age",?24)).toArray());??
- ??????
- ??????
- ????print("find?age?>=?24:?"?+?users.find(new?BasicDBObject("age",?new?BasicDBObject("$gte",?24))).toArray());??
- ????print("find?age?<=?24:?"?+?users.find(new?BasicDBObject("age",?new?BasicDBObject("$lte",?24))).toArray());??
- ??????
- ????print("查询age!=25:"?+?users.find(new?BasicDBObject("age",?new?BasicDBObject("$ne",?25))).toArray());??
- ????print("查询age?in?25/26/27:"?+?users.find(new?BasicDBObject("age",?new?BasicDBObject(QueryOperators.IN,?new?int[]?{?25,?26,?27?}))).toArray());??
- ????print("查询age?not?in?25/26/27:"?+?users.find(new?BasicDBObject("age",?new?BasicDBObject(QueryOperators.NIN,?new?int[]?{?25,?26,?27?}))).toArray());??
- ????print("查询age?exists?排序:"?+?users.find(new?BasicDBObject("age",?new?BasicDBObject(QueryOperators.EXISTS,?true))).toArray());??
- ??????
- ????print("只查询age属性:"?+?users.find(null,?new?BasicDBObject("age",?true)).toArray());??
- ????print("只查属性:"?+?users.find(null,?new?BasicDBObject("age",?true),?0,?2).toArray());??
- ????print("只查属性:"?+?users.find(null,?new?BasicDBObject("age",?true),?0,?2,?Bytes.QUERYOPTION_NOTIMEOUT).toArray());??
- ??????
- ??????
- ????print("findOne:?"?+?users.findOne());??
- ????print("findOne:?"?+?users.findOne(new?BasicDBObject("age",?26)));??
- ????print("findOne:?"?+?users.findOne(new?BasicDBObject("age",?26),?new?BasicDBObject("name",?true)));??
- ??????
- ??????
- ????print("findAndRemove?查询age=25的数据,并且删除:?"?+?users.findAndRemove(new?BasicDBObject("age",?25)));??
- ??????
- ??????
- ????print("findAndModify:?"?+?users.findAndModify(new?BasicDBObject("age",?26),?new?BasicDBObject("name",?"Abc")));??
- ????print("findAndModify:?"?+?users.findAndModify(??
- ????????new?BasicDBObject("age",?28),???
- ????????new?BasicDBObject("name",?true),???
- ????????new?BasicDBObject("age",?true),???
- ????????false,???
- ????????new?BasicDBObject("name",?"Abc"),???
- ????????true,???
- ????????true));??
- ??????
- ????queryAll();??
- }??
mongoDB不支持联合查询、子查询,这需要我们自己在程序中完成。将查询的结果集在Java查询中进行需要的过滤即可。
7、 其他操作
[java] view plaincopy
?
-
public?void?testOthers()?{??
- ????DBObject?user?=?new?BasicDBObject();??
- ????user.put("name",?"hoojo");??
- ????user.put("age",?24);??
- ??????
- ??????
- ????print("serialize:?"?+?JSON.serialize(user));??
- ??????
- ????print("parse:?"?+?JSON.parse("{?\"name\"?:?\"hoojo\"?,?\"age\"?:?24}"));??
- ??????
- ????print("判断temp?Collection是否存在:?"?+?db.collectionExists("temp"));??
- ??????
- ??????
- ????if?(!db.collectionExists("temp"))?{??
- ????????DBObject?options?=?new?BasicDBObject();??
- ????????options.put("size",?20);??
- ????????options.put("capped",?20);??
- ????????options.put("max",?20);??
- ????????print(db.createCollection("account",?options));??
- ????}??
- ??????
- ??????
- ????db.setReadOnly(true);??
- ??????
- ??????
- ????db.getCollection("test").save(user);??
- }??
好了,这里基本上就介绍这么多Java操作MongoDB的方法。其他的东西还需要你自己多多研究。上面操作MongoDB的方法都是一些常用的方法,比较简单。如果有什么问题,欢迎随时和我联系,一起交流沟通。