MongoDB基本用法(增删改高级查询、mapreduce)

TestCase.java

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

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

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