【MongoDB】5.MongoDB與java的簡單結合


1.首先 你的清楚你的MongoDB的版本是多少  就下載對應的架包

下載地址如下:

http://mongodb.github.io/mongo-java-driver/  

2.新建一個項目  把架包扔進去,並Build path到你的項目下【如果用於測試,請如下 多用一個架包】

 

3.新建一個MongoConnection類 用來獲取MongoDB的連接對象:

 1 package com.mongo.util;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import com.mongodb.MongoClient;
 7 import com.mongodb.MongoCredential;
 8 import com.mongodb.ServerAddress;
 9 import com.mongodb.client.MongoDatabase;
10 
11 public class MongoConnection {
12      
13     /**
14      * 需要驗證用戶名  密碼的 MongoDB的連接方式   com.mongodb.MongoClient.getDatabase("數據庫名")
15      * @return
16      */
17     public MongoDatabase getConnection() {
18          try {  
19                 //連接到MongoDB服務 如果是遠程連接可以替換“localhost”為服務器所在IP地址  
20                 //ServerAddress()兩個參數分別為 服務器地址 和 端口  
21                 ServerAddress serverAddress = new ServerAddress("localhost",27017);  
22                 List<ServerAddress> addrs = new ArrayList<ServerAddress>();  
23                 addrs.add(serverAddress);  
24                   
25                 //MongoCredential.createScramSha1Credential()三個參數分別為 用戶名 數據庫名稱 密碼  
26                 MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());  
27                 List<MongoCredential> credentials = new ArrayList<MongoCredential>();  
28                 credentials.add(credential);  
29                   
30                 //通過連接認證獲取MongoDB連接  
31                 MongoClient mongoClient = new MongoClient(addrs,credentials);  
32                   
33                 //連接到數據庫  
34                 MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");  
35                 System.out.println("連接成功");  
36                 return mongoDatabase;
37             } catch (Exception e) {  
38                 System.err.println( e.getClass().getName() + ": " + e.getMessage() );  
39             }  
40          return null;
41     }
42     
43     /**
44      * 不需要驗證  用戶名+密碼  的獲取連接的方式 com.mongodb.MongoClient.getDatabase("數據庫名")
45      * @return
46      */
47     public MongoDatabase getConnectionBasis(){
48         try {
49             //連接到mongodb服務
50             MongoClient mongoClient = new MongoClient("localhost",27017);
51             MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");
52             System.out.println("連接成功");
53             return mongoDatabase;
54         } catch (Exception e) {
55             System.out.println(e.getClass().getName()+":"+e.getMessage());
56         }
57         return null;
58     }
59     
60 }
View Code

4.再建一個類 用來測試 你的增刪改查

  1 package com.mongo.test;
  2 
  3 
  4 import java.text.SimpleDateFormat;
  5 import java.util.ArrayList;
  6 import java.util.List;
  7 
  8 import org.bson.Document;
  9 import org.junit.Test;
 10 
 11 import com.mongo.util.MongoConnection;
 12 import com.mongodb.client.FindIterable;
 13 import com.mongodb.client.MongoCollection;
 14 import com.mongodb.client.MongoCursor;
 15 import com.mongodb.client.MongoDatabase;
 16 import com.mongodb.client.model.Filters;
 17 
 18 public class MongoTest {
 19     
 20     MongoConnection connection = new MongoConnection();
 21     //連接到數據庫
 22     MongoDatabase mongoDatabase = connection.getConnectionBasis();
 23     
 24     
 25     @Test
 26     public void test(){
 27         //createCollection();//創建   集合 一次就好
 28         MongoCollection<Document> collection = getCollection();
 29         insertDomcument(collection);
 30         findAll(collection);
 31         //delete(collection);
 32     }
 33     
 34     /**
 35      * 創建  集合【對應RDBMS 中的數據表】 com.mongodb.client.MongoDatabase.createCollection("集合名")
 36      */
 37     public void createCollection(){
 38         mongoDatabase.createCollection("testConllection");
 39         System.out.println("創建集合成功");
 40     }
 41     
 42     /**
 43      * 獲取  集合【對應RDBMS 中的數據表】com.mongodb.client.MongoDatabase.getCollection("集合名")
 44      */
 45     public MongoCollection<Document> getCollection(){
 46         MongoCollection<Document>  collection = mongoDatabase.getCollection("testConllection");
 47         System.out.println("轉換到指定集合");
 48         return collection;
 49     }
 50     
 51     /**
 52      * 插入  文檔【對應RDBMS 中的一條數據】com.mongodb.client.MongoCollection<Document>.insertOne()/insertMany()
 53      */
 54     public void insertDomcument(MongoCollection<Document> collection){
 55         /** 
 56         * 1. 創建文檔 org.bson.Document 參數為key-value的格式 
 57         * 2. 創建文檔集合List<Document> 
 58         * 3. 將文檔集合插入數據庫集合中 mongoCollection.insertMany(List<Document>) 插入單個文檔可以用 mongoCollection.insertOne(Document) 
 59         * */
 60         Document document = new Document();
 61         document.append("name", "走四方");
 62         document.append("age", 23);
 63         document.append("url", "www.baidu.com");
 64         
 65         List<Document> list = new ArrayList<Document>();
 66         list.add(document);
 67         
 68         collection.insertMany(list);
 69         System.out.println("插入文檔成功");
 70         
 71         //插入 單條數據
 72         Document  t = new Document();
 73         t.append("name", "走什么");
 74         t.append("age", 26);
 75         t.append("url", "www.agen.cn");
 76         
 77         collection.insertOne(t);
 78         System.out.println("插入單條數據成功");
 79     }
 80     
 81     /**
 82      * 查詢  所有文檔【表內 數據】com.mongodb.client.MongoCollection<Document>.find()
 83      * 查詢  本條數據的時間節點   _id采用ObjectId格式
 84      * 
 85      * ObjectId 是一個12字節 BSON 類型數據,有以下格式:
 86             前4個字節表示時間戳
 87             接下來的3個字節是機器標識碼
 88             緊接的兩個字節由進程id組成(PID)
 89             最后三個字節是隨機數。
 90      */
 91     public void findAll(MongoCollection<Document> collection){
 92         /** 
 93         * 1. 獲取迭代器FindIterable<Document> 
 94         * 2. 獲取游標MongoCursor<Document> 
 95         * 3. 通過游標遍歷檢索出的文檔集合 
 96         * */
 97          FindIterable<Document> findIterable = collection.find();
 98          MongoCursor<Document> mongoCursor = findIterable.iterator();
 99          while(mongoCursor.hasNext()){
100              Document document = mongoCursor.next();
101              System.out.println("MongoDB數據:"+document);
102              System.out.println("本地時間:"+new SimpleDateFormat().format(document.getObjectId("_id").getDate()));
103          }
104     }
105     
106     /**
107      * 更新   所有文檔【表內  數據】com.mongodb.client.MongoCollection<Document>.updateMany()
108      */
109     public void update(MongoCollection<Document> collection){
110         
111         collection.updateMany(Filters.eq("age", 26), new Document("$set",new Document("age",100)));
112         
113         FindIterable<Document> findIterable = collection.find();
114         MongoCursor<Document> cursor = findIterable.iterator();
115         while (cursor.hasNext()) {
116             System.out.println("更新后的MongoDB數據:"+cursor.next());
117         }
118     }
119     
120     
121     /**
122      * 刪除  文檔 com.mongodb.client.MongoCollection<Document>.deleteMany()/deleteOne()
123      */
124     public void delete(MongoCollection<Document> collection){
125         // 刪除符合條件的 第一個文檔
126         collection.findOneAndDelete(Filters.eq("age", 26));
127         //刪除符合條件的  所有文檔
128         collection.deleteMany(Filters.gte("age", 20));
129         
130         FindIterable<Document> findIterable = collection.find();
131         MongoCursor<Document> cursor = findIterable.iterator();
132         while(cursor.hasNext()){
133             System.out.println("刪除后的MongoDB數據:"+cursor.next());
134         }
135     }
136     
137     
138     
139     
140     
141 }
View Code

 

5.完成  自行研究


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM