MongoDB java api for 插入和单collection基本查询使用示例

来源:互联网 发布:新闻发布系统 java 编辑:程序博客网 时间:2024/06/05 18:37

原文地址:http://blog.csdn.net/tujiyue/archive/2011/05/21/6436312.aspx

 

1.首先为我们要准备操作的数据库添加一个用户验证:

[java] view plaincopyprint?
  1. [root@localhost src]# mongo  
  2. MongoDB shell version: 1.8.1  
  3. connecting to: test  
  4. > show dbs;  
  5. admin   (empty)  
  6. local   (empty)  
  7. > db    
  8. test  
  9. > db.addUser("iwtxokhtd","123456");  
  10. {  
  11.         "user" : "iwtxokhtd",  
  12.         "readOnly" : false,  
  13.         "pwd" : "c728e00401a72282a2919648723dbff7"  
  14. }  
  15. > show collections;  
  16. system.indexes  
  17. system.users  
  18. > db.system.users.find();  
  19. "_id" : ObjectId("4dd73c7d247cb75e4995757b"), "user" : "iwtxokhtd""readOnly" : false"pwd" : "c728e00401a72282a2919648723dbff7" }  
  20. >   

 

2. 下载MongoDB的java api包,mongo-2.5.3.jar,建立一个java工程如下:

  

3. 示例代码:

[java] view plaincopyprint?
  1. /** 
  2.  * MongoDBTest 
  3.  * MongoDB java api的初步使用示例 
  4.  * 此次只介绍一下insert和query(基本单collection查询)两种操作 
  5.  */  
  6. package com.labci.mongodb.test;  
  7. import java.net.UnknownHostException;  
  8. import java.util.Iterator;  
  9. import java.util.regex.Pattern;  
  10. import com.mongodb.BasicDBObject;  
  11. import com.mongodb.DB;  
  12. import com.mongodb.DBCollection;  
  13. import com.mongodb.DBCursor;  
  14. import com.mongodb.DBObject;  
  15. import com.mongodb.Mongo;  
  16. import com.mongodb.MongoException;  
  17. /** 
  18.  * @author Bill Tu(tujiyue/iwtxokhtd) 
  19.  * May 21, 2011[12:06:41 PM] 
  20.  * 
  21.  */  
  22. public class MongoDBJavaAPITest {  
  23.     private static final String HOST = "192.168.1.86";  
  24.     private static final int PORT = 27017;  
  25.     private static final String USER = "iwtxokhtd";  
  26.     private static final String PASSWORD = "123456";  
  27.     private static final String DB_NAME = "test";  
  28.     private static final String COLLECTION = "data_test";  
  29.     private static final int SIZE = 10;  
  30.       
  31.     /** 
  32.      * 进行测试 
  33.      * @throws Exception 
  34.      */  
  35.     private static void initTest() throws Exception{  
  36.         try {  
  37.             Mongo conn=new Mongo(HOST,PORT);//建立数据库连接  
  38.             DB testDB=conn.getDB(DB_NAME);//取得test数据库  
  39.             /** 
  40.              * 如果test数据库没有设定用户权限认证,则无需下面的验证 
  41.              */  
  42.             boolean loginSuccess=testDB.authenticate(USER, PASSWORD.toCharArray());  
  43.             if(!loginSuccess){  
  44.                 throw new Exception("登录"+DB_NAME+"验证失败,请确认用户名和密码");  
  45.             }  
  46.             /** 
  47.              * 如果COLLECTION不存在,则MongoDB会自动为你创建此collection 
  48.              */  
  49.             DBCollection collection=testDB.getCollection(COLLECTION);  
  50.             //开始插入数据操作  
  51.             insertData(collection,SIZE);  
  52.             //查询操作  
  53.             findData(collection);  
  54.               
  55.         } catch (UnknownHostException e) {  
  56.             e.printStackTrace();  
  57.         } catch (MongoException e) {  
  58.             e.printStackTrace();  
  59.         }  
  60.     }  
  61.       
  62.     /** 
  63.      * 向collection插入size条记录 
  64.      */  
  65.     private static void insertData(DBCollection collection,int size){  
  66.         long beginTime=System.currentTimeMillis();  
  67.         for(int i=1;i<=size;i++){  
  68.             BasicDBObject basic=new BasicDBObject();  
  69.             basic.put("userId""1001017"+i);  
  70.             basic.put("userName""Bill Tu"+i);  
  71.             basic.put("gender""m"+i);  
  72.               
  73.             BasicDBObject interests=new BasicDBObject();  
  74.             interests.put("game""game"+i);  
  75.             interests.put("ball""ball"+i);  
  76.             interests.put("other""nothing"+i);  
  77.               
  78.             basic.put("interests", interests);  
  79.               
  80.             collection.insert(basic);  
  81.         }  
  82.         long endTime=System.currentTimeMillis();  
  83.         System.out.println("插入用时:"+(endTime-beginTime)+" ms");  
  84.           
  85.     }  
  86.       
  87.     /** 
  88.      * 根据指定collection单collection查询 
  89.      *  
  90.      */  
  91.     private static void findData(DBCollection collection){  
  92.         //查询所有记录  
  93.         long beginTime=System.currentTimeMillis();  
  94.         DBCursor queryAll=collection.find();  
  95.         System.out.println("所有记录:");  
  96.         for(Iterator<DBObject> iter=queryAll.iterator();iter.hasNext();){  
  97.             System.out.println(iter.next());  
  98.         }  
  99.         long endTime=System.currentTimeMillis();  
  100.         System.out.println("查询所有记录用时:"+(endTime-beginTime)+" ms");  
  101.           
  102.         //只看第一条记录  
  103.         DBObject queryFirstRecord=collection.findOne();  
  104.         System.out.println("第一条记录:"+queryFirstRecord);  
  105.           
  106.         //根据单条件查询  
  107.         DBObject singleCondition_query=new BasicDBObject();  
  108.         //根据userId=10010172条件来查  
  109.         singleCondition_query.put("userId""10010172");  
  110.           
  111.         DBCursor singleQueryResult=collection.find(singleCondition_query);  
  112.         for(Iterator<DBObject> iter=singleQueryResult.iterator();iter.hasNext();){  
  113.             System.out.println("按单条件查询结果:"+iter.next());  
  114.         }  
  115.           
  116.         //根据复合条件来查询  
  117.         DBObject compoundCondition_query=new BasicDBObject();  
  118.         //根据userId=10010171&userName=Bill Tu1来查询  
  119.         compoundCondition_query.put("userId""10010171");  
  120.         compoundCondition_query.put("userName""Bill Tu1");  
  121.         DBCursor compoundQueryResult=collection.find(compoundCondition_query);  
  122.         System.out.println("按复合条件查询结果:");  
  123.         for(Iterator<DBObject> iter=compoundQueryResult.iterator();iter.hasNext();){  
  124.             System.out.println(iter.next());  
  125.         }  
  126.           
  127.         //in查询  
  128.         DBObject in_data=new BasicDBObject("$in",new Object[]{"10010171","10010172"});  
  129.         //根据userId in('10010171','10010172')查询  
  130.         DBObject in_query=new BasicDBObject();  
  131.         in_query.put("userId", in_data);  
  132.         DBCursor inQueryResult=collection.find(in_query);  
  133.         System.out.println("按in条件查询结果:");  
  134.         for(Iterator<DBObject> iter=inQueryResult.iterator();iter.hasNext();){  
  135.             System.out.println(iter.next());  
  136.         }  
  137.           
  138.         //模糊查询  
  139.         DBObject fuzzy_query=new BasicDBObject();  
  140.         String keyWord="10010171";  
  141.         Pattern pattern = Pattern.compile("^" + keyWord + ".*$", Pattern.CASE_INSENSITIVE);   
  142.         //根据userId like 1001017%查询  
  143.         fuzzy_query.put("userId", pattern);  
  144.         DBCursor fuzzyQueryResult=collection.find(fuzzy_query);  
  145.         System.out.println("按模糊条件查询结果:");  
  146.         for(Iterator<DBObject> iter=fuzzyQueryResult.iterator();iter.hasNext();){  
  147.             System.out.println(iter.next());  
  148.         }  
  149.           
  150.     }  
  151.       
  152.     /** 
  153.      * @param args 
  154.      */  
  155.     public static void main(String[] args) {  
  156.         try {  
  157.             initTest();  
  158.         } catch (Exception e) {  
  159.             e.printStackTrace();  
  160.         }  
  161.     }  
  162. }  

 

4. 运行结果:

[java] view plaincopyprint?
  1.  插入记录用时:16 ms  
  2. 所有记录:  
  3. "_id" : { "$oid" : "4dd747cb3a491e68a1a84a30"} , "userId" : "10010171" , "userName" : "Bill Tu1" , "gender" : "m1" , "interests" : { "game" : "game1" , "ball" : "ball1" , "other" : "nothing1"}}  
  4. "_id" : { "$oid" : "4dd747cb3a491e68a1a84a31"} , "userId" : "10010172" , "userName" : "Bill Tu2" , "gender" : "m2" , "interests" : { "game" : "game2" , "ball" : "ball2" , "other" : "nothing2"}}  
  5. "_id" : { "$oid" : "4dd747cb3a491e68a1a84a32"} , "userId" : "10010173" , "userName" : "Bill Tu3" , "gender" : "m3" , "interests" : { "game" : "game3" , "ball" : "ball3" , "other" : "nothing3"}}  
  6. "_id" : { "$oid" : "4dd747cb3a491e68a1a84a33"} , "userId" : "10010174" , "userName" : "Bill Tu4" , "gender" : "m4" , "interests" : { "game" : "game4" , "ball" : "ball4" , "other" : "nothing4"}}  
  7. "_id" : { "$oid" : "4dd747cb3a491e68a1a84a34"} , "userId" : "10010175" , "userName" : "Bill Tu5" , "gender" : "m5" , "interests" : { "game" : "game5" , "ball" : "ball5" , "other" : "nothing5"}}  
  8. "_id" : { "$oid" : "4dd747cb3a491e68a1a84a35"} , "userId" : "10010176" , "userName" : "Bill Tu6" , "gender" : "m6" , "interests" : { "game" : "game6" , "ball" : "ball6" , "other" : "nothing6"}}  
  9. "_id" : { "$oid" : "4dd747cb3a491e68a1a84a36"} , "userId" : "10010177" , "userName" : "Bill Tu7" , "gender" : "m7" , "interests" : { "game" : "game7" , "ball" : "ball7" , "other" : "nothing7"}}  
  10. "_id" : { "$oid" : "4dd747cb3a491e68a1a84a37"} , "userId" : "10010178" , "userName" : "Bill Tu8" , "gender" : "m8" , "interests" : { "game" : "game8" , "ball" : "ball8" , "other" : "nothing8"}}  
  11. "_id" : { "$oid" : "4dd747cb3a491e68a1a84a38"} , "userId" : "10010179" , "userName" : "Bill Tu9" , "gender" : "m9" , "interests" : { "game" : "game9" , "ball" : "ball9" , "other" : "nothing9"}}  
  12. "_id" : { "$oid" : "4dd747cb3a491e68a1a84a39"} , "userId" : "100101710" , "userName" : "Bill Tu10" , "gender" : "m10" , "interests" : { "game" : "game10" , "ball" : "ball10" , "other" : "nothing10"}}  
  13. 查询所有记录用时:16 ms  
  14. 第一条记录:{ "_id" : { "$oid" : "4dd747cb3a491e68a1a84a30"} , "userId" : "10010171" , "userName" : "Bill Tu1" , "gender" : "m1" , "interests" : { "game" : "game1" , "ball" : "ball1" , "other" : "nothing1"}}  
  15. 按单条件查询结果:{ "_id" : { "$oid" : "4dd747cb3a491e68a1a84a31"} , "userId" : "10010172" , "userName" : "Bill Tu2" , "gender" : "m2" , "interests" : { "game" : "game2" , "ball" : "ball2" , "other" : "nothing2"}}  
  16. 按复合条件查询结果:  
  17. "_id" : { "$oid" : "4dd747cb3a491e68a1a84a30"} , "userId" : "10010171" , "userName" : "Bill Tu1" , "gender" : "m1" , "interests" : { "game" : "game1" , "ball" : "ball1" , "other" : "nothing1"}}  
  18. 按in条件查询结果:  
  19. "_id" : { "$oid" : "4dd747cb3a491e68a1a84a30"} , "userId" : "10010171" , "userName" : "Bill Tu1" , "gender" : "m1" , "interests" : { "game" : "game1" , "ball" : "ball1" , "other" : "nothing1"}}  
  20. "_id" : { "$oid" : "4dd747cb3a491e68a1a84a31"} , "userId" : "10010172" , "userName" : "Bill Tu2" , "gender" : "m2" , "interests" : { "game" : "game2" , "ball" : "ball2" , "other" : "nothing2"}}  
  21. 按模糊条件查询结果:  
  22. "_id" : { "$oid" : "4dd747cb3a491e68a1a84a30"} , "userId" : "10010171" , "userName" : "Bill Tu1" , "gender" : "m1" , "interests" : { "game" : "game1" , "ball" : "ball1" , "other" : "nothing1"}}  
  23. "_id" : { "$oid" : "4dd747cb3a491e68a1a84a39"} , "userId" : "100101710" , "userName" : "Bill Tu10" , "gender" : "m10" , "interests" : { "game" : "game10" , "ball" : "ball10" , "other" : "nothing10"}} 

原创粉丝点击