TestCase.java

  1. package com.wujintao.mongo;
  2. import java.net.UnknownHostException;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import java.util.Set;
  6. import java.util.regex.Pattern;
  7. import org.junit.Test;
  8. import com.mongodb.AggregationOutput;
  9. import com.mongodb.BasicDBList;
  10. import com.mongodb.BasicDBObject;
  11. import com.mongodb.BasicDBObjectBuilder;
  12. import com.mongodb.DB;
  13. import com.mongodb.DBCollection;
  14. import com.mongodb.DBCursor;
  15. import com.mongodb.DBObject;
  16. import com.mongodb.MapReduceCommand;
  17. import com.mongodb.MapReduceOutput;
  18. import com.mongodb.Mongo;
  19. import com.mongodb.QueryBuilder;
  20. import com.mongodb.WriteConcern;
  21. public class TestCase {
  22. //DBCursor cursor = coll.find(condition).addOption(Bytes.QUERYOPTION_NOTIMEOUT);//设置游标不要超时
  23. @Test
  24. /**
  25. * 获取所有数据库实例
  26. */
  27. public void testGetDBS() {
  28. List<String> dbnames = MongoUtil.getMong().getDatabaseNames();
  29. for (String dbname : dbnames) {
  30. System.out.println("dbname:" + dbname);
  31. }
  32. }
  33. @Test
  34. /**
  35. * 删除数据库
  36. */
  37. public void dropDatabase() {
  38. MongoUtil.getMong().dropDatabase("my_new_db");
  39. }
  40. @Test
  41. /**
  42. * 查询所有表名
  43. */
  44. public void getAllCollections() {
  45. Set<String> colls = MongoUtil.getDB().getCollectionNames();
  46. for (String s : colls) {
  47. System.out.println(s);
  48. }
  49. }
  50. @Test
  51. public void dropCollection() {
  52. MongoUtil.getColl("jellonwu").drop();
  53. }
  54. /**
  55. * 添加一条记录
  56. */
  57. @Test
  58. public void addData() {
  59. DBCollection coll = MongoUtil.getColl("wujintao");
  60. BasicDBObject doc = new BasicDBObject();
  61. doc.put("name", "MongoDB");
  62. doc.put("type", "database");
  63. doc.put("count", 1);
  64. BasicDBObject info = new BasicDBObject();
  65. info.put("x", 203);
  66. info.put("y", 102);
  67. doc.put("info", info);
  68. coll.insert(doc);
  69. // 设定write concern,以便操作失败时得到提示
  70. coll.setWriteConcern(WriteConcern.SAFE);
  71. }
  72. @Test
  73. /**
  74. * 创建索引
  75. */
  76. public void createIndex() {
  77. MongoUtil.getColl("wujintao").createIndex(new BasicDBObject("i", 1));
  78. }
  79. @Test
  80. /**
  81. * 获取索引信息
  82. */
  83. public void getIndexInfo() {
  84. List<DBObject> list = MongoUtil.getColl("hems_online").getIndexInfo();
  85. for (DBObject o : list) {
  86. System.out.println(o);
  87. }
  88. }
  89. @Test
  90. /**
  91. * 添加多条记录
  92. */
  93. public void addMultiData() {
  94. for (int i = 0; i < 100; i++) {
  95. MongoUtil.getColl("wujintao").insert(
  96. new BasicDBObject().append("i", i));
  97. }
  98. List<DBObject> docs = new ArrayList<DBObject>();
  99. for (int i = 0; i < 50; i++) {
  100. docs.add(new BasicDBObject().append("i", i));
  101. }
  102. MongoUtil.getColl("wujintao").insert(docs);
  103. // 设定write concern,以便操作失败时得到提示
  104. MongoUtil.getColl("wujintao").setWriteConcern(WriteConcern.SAFE);
  105. }
  106. @Test
  107. /**
  108. * 查找第一条记录
  109. */
  110. public void findOne() {
  111. DBObject myDoc = MongoUtil.getColl("wujintao").findOne();
  112. System.out.println(myDoc);
  113. }
  114. @Test
  115. /**
  116. * 获取表中所有记录条数
  117. */
  118. public void count() {
  119. System.out.println(MongoUtil.getColl("wujintao").getCount());
  120. System.out.println(MongoUtil.getColl("wujintao").count());
  121. }
  122. @Test
  123. /**
  124. * 获取查询结果集的记录数
  125. */
  126. public void getCount() {
  127. DBObject query = new BasicDBObject("name", "a");
  128. long count = MongoUtil.getColl("wujintao").count(query);
  129. System.out.println(count);
  130. }
  131. @Test
  132. /**
  133. * 查询所有结果
  134. */
  135. public void getAllDocuments() {
  136. DBCursor cursor = MongoUtil.getColl("wujintao").find();
  137. try {
  138. while (cursor.hasNext()) {
  139. System.out.println(cursor.next());
  140. }
  141. } finally {
  142. cursor.close();
  143. }
  144. }
  145. @Test
  146. /**
  147. * 按照一个条件查询
  148. */
  149. public void queryByConditionOne() {
  150. BasicDBObject query = new BasicDBObject();
  151. query.put("name", "MongoDB");
  152. DBCursor cursor = MongoUtil.getColl("wujintao").find(query);
  153. try {
  154. while (cursor.hasNext()) {
  155. System.out.println(cursor.next());
  156. }
  157. } finally {
  158. cursor.close();
  159. }
  160. }
  161. @Test
  162. /**
  163. * AND多条件查询,区间查询
  164. */
  165. public void queryMulti() {
  166. BasicDBObject query = new BasicDBObject();
  167. // 查询j不等于3,k大于10的结果集
  168. query.put("j", new BasicDBObject("$ne", 3));
  169. query.put("k", new BasicDBObject("$gt", 10));
  170. DBCursor cursor = MongoUtil.getColl("wujintao").find(query);
  171. try {
  172. while (cursor.hasNext()) {
  173. System.out.println(cursor.next());
  174. }
  175. } finally {
  176. cursor.close();
  177. }
  178. }
  179. @Test
  180. /**
  181. * 区间查询
  182. * select * from table where i >50
  183. */
  184. public void queryMulti2() {
  185. BasicDBObject query = new BasicDBObject();
  186. query = new BasicDBObject();
  187. query.put("i", new BasicDBObject("$gt", 50)); // e.g. find all where i >
  188. DBCursor cursor = MongoUtil.getColl("wujintao").find(query);
  189. try {
  190. while (cursor.hasNext()) {
  191. System.out.println(cursor.next());
  192. }
  193. } finally {
  194. cursor.close();
  195. }
  196. }
  197. @Test
  198. /**
  199. * 区间查询
  200. * select * from table where 20 < i <= 30
  201. //比较符
  202. //"$gt": 大于
  203. //"$gte":大于等于
  204. //"$lt": 小于
  205. //"$lte":小于等于
  206. //"$in": 包含
  207. */
  208. public void queryMulti3() {
  209. BasicDBObject query = new BasicDBObject();
  210. query = new BasicDBObject();
  211. query.put("i", new BasicDBObject("$gt", 20).append("$lte", 30));
  212. DBCursor cursor = MongoUtil.getColl("wujintao").find(query);
  213. try {
  214. while (cursor.hasNext()) {
  215. System.out.println(cursor.next());
  216. }
  217. } finally {
  218. cursor.close();
  219. }
  220. }
  221. /**
  222. * 组合in和and select * from test_Table where (a=5 or b=6) and (c=5 or d = 6)
  223. */
  224. public void queryMulti4() {
  225. BasicDBObject query11 = new BasicDBObject();
  226. query11.put("a", 1);
  227. BasicDBObject query12 = new BasicDBObject();
  228. query12.put("b", 2);
  229. List<BasicDBObject> orQueryList1 = new ArrayList<BasicDBObject>();
  230. orQueryList1.add(query11);
  231. orQueryList1.add(query12);
  232. BasicDBObject orQuery1 = new BasicDBObject("$or", orQueryList1);
  233. BasicDBObject query21 = new BasicDBObject();
  234. query21.put("c", 5);
  235. BasicDBObject query22 = new BasicDBObject();
  236. query22.put("d", 6);
  237. List<BasicDBObject> orQueryList2 = new ArrayList<BasicDBObject>();
  238. orQueryList2.add(query21);
  239. orQueryList2.add(query22);
  240. BasicDBObject orQuery2 = new BasicDBObject("$or", orQueryList2);
  241. List<BasicDBObject> orQueryCombinationList = new ArrayList<BasicDBObject>();
  242. orQueryCombinationList.add(orQuery1);
  243. orQueryCombinationList.add(orQuery2);
  244. BasicDBObject finalQuery = new BasicDBObject("$and",
  245. orQueryCombinationList);
  246. DBCursor cursor = MongoUtil.getColl("wujintao").find(finalQuery);
  247. }
  248. @Test
  249. /**
  250. * IN查询
  251. * if i need to query name in (a,b); just use { name : { $in : ['a', 'b'] } }
  252. * select * from things where name='a' or name='b'
  253. * @param coll
  254. */
  255. public void queryIn() {
  256. BasicDBList values = new BasicDBList();
  257. values.add("a");
  258. values.add("b");
  259. BasicDBObject in = new BasicDBObject("$in", values);
  260. DBCursor cursor = MongoUtil.getColl("wujintao").find(
  261. new BasicDBObject("name", in));
  262. try {
  263. while (cursor.hasNext()) {
  264. System.out.println(cursor.next());
  265. }
  266. } finally {
  267. cursor.close();
  268. }
  269. }
  270. @Test
  271. /**
  272. * 或查询
  273. * select * from table where name  = '12' or title = 'p'
  274. * @param coll
  275. */
  276. public void queryOr() {
  277. QueryBuilder query = new QueryBuilder();
  278. query.or(new BasicDBObject("name", 12), new BasicDBObject("title", "p"));
  279. DBCursor cursor = MongoUtil.getColl("wujintao").find(query.get()).addSpecial("$returnKey", "");
  280. try {
  281. while (cursor.hasNext()) {
  282. System.out.println(cursor.next());
  283. }
  284. } finally {
  285. cursor.close();
  286. }
  287. }
  288. @Test
  289. public void customQueryField() throws UnknownHostException{
  290. Mongo mongo = new Mongo("localhost", 27017);
  291. DB db = mongo.getDB("zhongsou_ad");
  292. BasicDBObjectBuilder bulder = new BasicDBObjectBuilder();
  293. bulder.add("times",1);
  294. bulder.add("aid",1);
  295. DBCursor cusor =  db.getCollection("ad_union_ad_c_1").find(new BasicDBObject(),bulder.get());
  296. for (DBObject dbObject : cusor) {
  297. System.out.println(dbObject);
  298. }
  299. }
  300. @Test
  301. public void mapReduce() throws UnknownHostException{
  302. Mongo mongo = new Mongo("localhost", 27017);
  303. DB db = mongo.getDB("zhongsou_ad");
  304. /***
  305. *  book1 = {name : "Understanding JAVA", pages : 100}
  306. *  book2 = {name : "Understanding JSON", pages : 200}
  307. *  db.books.save(book1)
  308. *  db.books.save(book2)
  309. *  book = {name : "Understanding XML", pages : 300}
  310. *  db.books.save(book)
  311. *  book = {name : "Understanding Web Services", pages : 400}
  312. *  db.books.save(book)
  313. *  book = {name : "Understanding Axis2", pages : 150}
  314. *  db.books.save(book)
  315. *
  316. var map = function() {
  317. var category;
  318. if ( this.pages >= 250 )
  319. category = 'Big Books';
  320. else
  321. category = "Small Books";
  322. emit(category, {name: this.name});
  323. };
  324. var reduce = function(key, values) {
  325. var sum = 0;
  326. values.forEach(function(doc) {
  327. sum += 1;
  328. });
  329. return {books: sum};
  330. };
  331. var count  = db.books.mapReduce(map, reduce, {out: "book_results"});
  332. */
  333. try {
  334. DBCollection books = db.getCollection("books");
  335. BasicDBObject book = new BasicDBObject();
  336. book.put("name", "Understanding JAVA");
  337. book.put("pages", 100);
  338. books.insert(book);
  339. book = new BasicDBObject();
  340. book.put("name", "Understanding JSON");
  341. book.put("pages", 200);
  342. books.insert(book);
  343. book = new BasicDBObject();
  344. book.put("name", "Understanding XML");
  345. book.put("pages", 300);
  346. books.insert(book);
  347. book = new BasicDBObject();
  348. book.put("name", "Understanding Web Services");
  349. book.put("pages", 400);
  350. books.insert(book);
  351. book = new BasicDBObject();
  352. book.put("name", "Understanding Axis2");
  353. book.put("pages", 150);
  354. books.insert(book);
  355. String map = "function() { "+
  356. "var category; " +
  357. "if ( this.pages >= 250 ) "+
  358. "category = 'Big Books'; " +
  359. "else " +
  360. "category = 'Small Books'; "+
  361. "emit(category, {name: this.name});}";
  362. String reduce = "function(key, values) { " +
  363. "var sum = 0; " +
  364. "values.forEach(function(doc) { " +
  365. "sum += 1; "+
  366. "}); " +
  367. "return {books: sum};} ";
  368. MapReduceCommand cmd = new MapReduceCommand(books, map, reduce,
  369. null, MapReduceCommand.OutputType.INLINE, null);
  370. MapReduceOutput out = books.mapReduce(cmd);
  371. for (DBObject o : out.results()) {
  372. System.out.println(o.toString());
  373. }
  374. } catch (Exception e) {
  375. e.printStackTrace();
  376. }
  377. }
  378. @Test
  379. public void GroupByManyField() throws UnknownHostException{
  380. //此方法没有运行成功
  381. Mongo mongo = new Mongo("localhost", 27017);
  382. DB db = mongo.getDB("libary");
  383. DBCollection books = db.getCollection("books");
  384. BasicDBObject groupKeys = new BasicDBObject();
  385. groupKeys.put("total", new BasicDBObject("$sum","pages"));
  386. BasicDBObject condition = new BasicDBObject();
  387. condition.append("pages", new BasicDBObject().put("$gt", 0));
  388. String reduce = "function(key, values) { " +
  389. "var sum = 0; " +
  390. "values.forEach(function(doc) { " +
  391. "sum += 1; "+
  392. "}); " +
  393. "return {books: sum};} ";
  394. /**
  395. BasicDBList basicDBList = (BasicDBList)db.getCollection("mongodb中集合编码或者编码")
  396. .group(DBObject key,   --分组字段,即group by的字段
  397. DBObject cond,        --查询中where条件
  398. DBObject initial,     --初始化各字段的值
  399. String reduce,        --每个分组都需要执行的Function
  400. String finial         --终结Funciton对结果进行最终的处理
  401. */
  402. DBObject obj = books.group(groupKeys, condition,  new BasicDBObject(), reduce);
  403. System.out.println(obj);
  404. AggregationOutput ouput = books.aggregate(new BasicDBObject("$group",groupKeys));
  405. System.out.println(ouput.getCommandResult());
  406. System.out.println(books.find(new BasicDBObject("$group",groupKeys)));
  407. }
  408. @Test
  409. /**
  410. * 分页查询
  411. */
  412. public void pageQuery() {
  413. DBCursor cursor = MongoUtil.getColl("wujintao").find().skip(0)
  414. .limit(10);
  415. while (cursor.hasNext()) {
  416. System.out.println(cursor.next());
  417. }
  418. }
  419. /**
  420. * 模糊查询
  421. */
  422. public void likeQuery() {
  423. Pattern john = Pattern.compile("joh?n");
  424. BasicDBObject query = new BasicDBObject("name", john);
  425. // finds all people with "name" matching /joh?n/i
  426. DBCursor cursor = MongoUtil.getColl("wujintao").find(query);
  427. }
  428. @Test
  429. /**
  430. * 条件删除
  431. */
  432. public void delete() {
  433. BasicDBObject query = new BasicDBObject();
  434. query.put("name", "xxx");
  435. // 找到并且删除,并返回删除的对象
  436. DBObject removeObj = MongoUtil.getColl("wujintao").findAndRemove(query);
  437. System.out.println(removeObj);
  438. }
  439. @Test
  440. /**
  441. * 更新
  442. */
  443. public void update() {
  444. BasicDBObject query = new BasicDBObject();
  445. query.put("name", "liu");
  446. DBObject stuFound = MongoUtil.getColl("wujintao").findOne(query);
  447. stuFound.put("name", stuFound.get("name") + "update_1");
  448. MongoUtil.getColl("wujintao").update(query, stuFound);
  449. }
  450. }

这里面涉及到的MongoUtil.java如下:

  1. package com.wujintao.mongo;
  2. import java.net.UnknownHostException;
  3. import org.apache.commons.logging.Log;
  4. import org.apache.commons.logging.LogFactory;
  5. import com.mongodb.DB;
  6. import com.mongodb.DBCollection;
  7. import com.mongodb.Mongo;
  8. /**
  9. * to see:http://www.mongodb.org/display/DOCS/Java+Driver+Concurrency
  10. * Mongo工具类:设计为单例模式,每当月份发生变化,数据库连接名称就会发生变化,这是业务规则
  11. * 因 MongoDB的Java驱动是线程安全的,对于一般的应用,只要一个Mongo实例即可,Mongo有个内置的连接池(池大小默认为10个)。
  12. * 对于有大量写和读的环境中,为了确保在一个Session中使用同一个DB时,我们可以用以下方式保证一致性:
  13. *   DB mdb = mongo.getDB('dbname');
  14. *   mdb.requestStart();
  15. *   // 业务代码
  16. *   mdb.requestDone();
  17. * DB和DBCollection是绝对线程安全的
  18. * @author wujintao
  19. */
  20. public class MongoUtil{
  21. private static Mongo mongo;
  22. private static DBCollection coll;
  23. private static Log log = LogFactory.getLog(MongoUtil.class);
  24. private static DB db;
  25. static{
  26. try {
  27. MongoOptions options = new MongoOptions();
  28. options.autoConnectRetry = true;
  29. options.connectionsPerHost = 1000;
  30. options.maxWaitTime = 5000;
  31. options.socketTimeout = 0;
  32. options.connectTimeout = 15000;
  33. options.threadsAllowedToBlockForConnectionMultiplier = 5000;
  34. //事实上,Mongo实例代表了一个数据库连接池,即使在多线程的环境中,一个Mongo实例对我们来说已经足够了
  35. mongo = new Mongo(new ServerAddress(DBMongoConfig.getHost(),DBMongoConfig.getPort()),options);
  36. //mongo = new Mongo(DBMongoConfig.getHost(),DBMongoConfig.getPort());
  37. // or, to connect to a replica set, supply a seed list of members
  38. // Mongo m = new Mongo(Arrays.asList(new ServerAddress("localhost",
  39. // 27017),
  40. // new ServerAddress("localhost", 27018),
  41. // new ServerAddress("localhost", 27019)));
  42. // 注意Mongo已经实现了连接池,并且是线程安全的。
  43. // 大部分用户使用mongodb都在安全内网下,但如果将mongodb设为安全验证模式,就需要在客户端提供用户名和密码:
  44. // boolean auth = db.authenticate(myUserName, myPassword);
  45. } catch (UnknownHostException e) {
  46. log.info("get mongo instance failed");
  47. }
  48. }
  49. public static DB getDB(){
  50. if(db==null){
  51. db = mongo.getDB(DBMongoConfig.getDbname());
  52. }
  53. return db;
  54. }
  55. public static Mongo getMong(){
  56. return mongo;
  57. }
  58. public static DBCollection getColl(String collname){
  59. return getDB().getCollection(collname);
  60. }
  61. }

MongoDB基本用法(增删改高级查询、mapreduce)的更多相关文章

  1. 封装对MongoDB数据库的增删改查访问方法(基于MongoDB官方发布的C#驱动)

    本文利用MongoDB官方发布的C#驱动,封装了对MongoDB数据库的增删改查访问方法.先用官方提供的mongo-csharp-driver ,当前版本为1.7.0.4714 编写数据库访问帮助类 ...

  2. 利用koa实现mongodb数据库的增删改查

    概述 使用koa免不了要操纵数据库,现阶段流行的数据库是mongoDB,所以我研究了一下koa里面mongoDB数据库的增删改查,记录下来,供以后开发时参考,相信对其他人也有用. 源代码请看:我的gi ...

  3. MongoDB --- 02. 基本操作,增删改查,数据类型,比较符,高级用法,pymongo

    一.基本操作 . mongod 启动服务端 2. mongo 启动客户端 3. show databses 查看本地磁盘的数据库 4. use 库名 切换到要使用的数据库 5. db 查看当前使用的数 ...

  4. webpack4+express+mongodb+vue 实现增删改查

    在讲解之前,我们先来看看效果如下所示: 1)整个页面的效果如下: 2) 新增数据效果如下: 3) 新增成功如下: 4) 编辑数据效果如下: 5) 编辑成功效果如下: 6) 删除数据效果如下: 7) 删 ...

  5. MongoDB学习之--增删改查(1)

    本文是对mongodb学习的一点笔记,主要介绍最简单的增删改操作,初学,看着API,有什么错误,希望大家指正:(使用官方驱动) 1.增 增加操作是最简单的,构造bsonDcument插入即可: 方式1 ...

  6. python连接集群mongodb,封装增删改查

    1.下载pymongo pip install pymongo 2.直接上代码 [ini配置文件] 封装读ini省略~~ [db.py] class Database(): def __init__( ...

  7. nodejs对mongodb数据库的增删改查操作(转载)

    首先要确保mongodb的正确安装,安装参照:http://docs.mongodb.org/manual/tutorial/install-mongodb-on-debian-or-ubuntu-l ...

  8. 69.nodejs对mongodb数据库的增删改查操作

    转自:https://www.cnblogs.com/sexintercourse/p/6485381.html 首先要确保mongodb的正确安装,安装参照:http://docs.mongodb. ...

  9. javascript数组的增删改和查询

    数组的增删改操作 对数组的增删改操作进行总结,下面(一,二,三)是对数组的增加,修改,删除操作都会改变原来的数组. (一)增加 向末尾增加 push() 返回新增后的数组长度 arr[arr.leng ...

随机推荐

  1. sqlite3简单操作

    最近在操作公司视频设备的tutk转发服务器的时候,用到的数据库是sqlite,在此复习一下 目录 1 建立数据库档案 2 在sqlite3提示列下操作 3 SQL的指令格式 4 建立资料表 5 建立索 ...

  2. docker的介绍以及常用命令

    一.docker的介绍 1. Docker是什么? Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的Linux机器上,也可以实现虚 ...

  3. 如何到python模块路径linux

    执行命令whereis python即可显示出python相关的所有的路径,包括可执行文件路径,安装路径等,该方法适用于大部分类似的场景抄自百度知道

  4. bash脚本编程学习笔记(一)

    bash脚本语言,不同于C/C++是一种解释性语言.即在执行前不需要事先转变为可执行的二进制代码,而是每次执行时经解释器解释后执行.bash脚本语言是命令的堆砌,即按照实际需要,结合命令流程机制实现的 ...

  5. 使用服务器上的Jupyter notebook。

    1.jupyter notebook --generate-config #产生配置文件 2.from notebook.auth import passwd #进入python环境,生成密码密文.第 ...

  6. javascript获取wx.config内部字段解决微信分享

    转自:http://www.jb51.net/article/80679.htm 专题推荐:js微信开发_脚本之家 http://www.jb51.net/Special/879.htm 背景在微信分 ...

  7. iOS学习笔记(6)——翻译苹果文档About Windows and Views

    About Windows and Views 关于窗口和视图 In iOS, you use windows and views to present your application’s cont ...

  8. MySQL之查看数据库编码

    MySQL之查看数据库编码

  9. 1059 C语言竞赛 (20 分)

    #include <iostream> #include <iomanip> #include <cmath> using namespace std; <& ...

  10. 数组或者stack

    数组 clear1(long long int array[], size_t int size) { ; i < size; i += ) array[i] = ; } li x5, // i ...