溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

mongodb中如何安裝java

發(fā)布時間:2021-07-30 15:55:05 來源:億速云 閱讀:103 作者:Leah 欄目:大數據

今天就跟大家聊聊有關mongodb中如何安裝java,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。

一、 安裝

mongodb中如何安裝java

環(huán)境變量設置

mongodb中如何安裝java

mongodb中如何安裝java

創(chuàng)建數據目錄,data文件夾,conf文件夾,db文件夾,log文件夾

mongodb中如何安裝java

mongodb中如何安裝java

創(chuàng)建配置文件mongod.cfg和日志文件。配置文件自己修改成相應的地址

mongodb中如何安裝java

systemLog:
    destination: file
    path: D:\mongodb-4.0.3\data\log\mongod.log
storage:
    dbPath: D:\mongodb-4.0.3\data\db

cmd下安裝成服務

mongod --config "D:\mongodb-4.0.3\conf\mongod.cfg">

啟動服務

net start MongoDB

ps.
net stop MongoDB 停止服務

mongod --remove 卸載服務

mongodb中如何安裝java

二、 使用

連接MongoDB,第一次是這樣的,他提示你要加個密碼

mongodb中如何安裝java

選擇admin數據庫

use admin

創(chuàng)建用戶

db.createUser( { 
user: "admin", //用戶名 
pwd: "123456", //密碼 
roles: [ { role: "root", db: "admin"> 
user文檔字段介紹:
    user字段,為新用戶的名字;
    pwd字段,用戶的密碼;
    cusomData字段,為任意內容,例如可以為用戶全名介紹;
    roles字段,指定用戶的角色,可以用一個空數組給新用戶設定空角色;

Built-In Roles(內置角色):
    1. 數據庫用戶角色:read、readWrite;
    2. 數據庫管理角色:dbAdmin、dbOwner、userAdmin;
    3. 集群管理角色:clusterAdmin、clusterManager、clusterMonitor、hostManager;
    4. 備份恢復角色:backup、restore;
    5. 所有數據庫角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase
    6. 超級用戶角色:root  
    // 這里還有幾個角色間接或直接提供了系統(tǒng)超級用戶的訪問(dbOwner 、userAdmin、userAdminAnyDatabase)
    7. 內部角色:__system 卸載服務,重裝再啟動,注意--auth mongod --auth --config "D:\mongodb-4.0.3\conf\mongod.cfg" --install net start MongoDB

net stop MongoDB 停止服務

mongod --remove 卸載服務 此時啟動mongo不使用密碼登錄則看起來成功進入實際4.正確的啟動mongo --port 27017 -u "admin" -p "123456" --authenticationDatabase "admin"  四、 java使用非maven項目可自行下載jar包 http://central.maven.org/maven2/org/mongodb/mongo-java-driver/3.2.2/mongo-java-driver-3.2.2.jarpom.xml<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver</artifactId>
            <version>3.8.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mongodb/mongodb-driver-core -->
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver-core</artifactId>
            <version>3.8.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mongodb/bson -->
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>bson</artifactId>
            <version>3.8.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies> mongodb工具類:public enum MongoUtil {
 45      /**
 46      * 定義一個枚舉的元素,它代表此類的一個實例
 47      */
 48     instance;
 49 
 50     private static MongoClient mongoClient;
 51 
 52     static {
 53         System.out.println("===============MongoDBUtil初始化========================");
 54         String ip = "192.168.1.75";
 55         int port =27017;
 56         instance.mongoClient = new MongoClient(ip, port);
 57         // 大部分用戶使用mongodb都在安全內網下,但如果將mongodb設為安全驗證模式,就需要在客戶端提供用戶名和密碼:
 58         // boolean auth = db.authenticate(myUserName, myPassword);
 59         Builder options = new MongoClientOptions.Builder();
 60         options.cursorFinalizerEnabled(true);
 61         // options.autoConnectRetry(true);// 自動重連true
 62         // options.maxAutoConnectRetryTime(10); // the maximum auto connect retry time
 63         options.connectionsPerHost(300);// 連接池設置為300個連接,默認為100
 64         options.connectTimeout(30000);// 連接超時,推薦>3000毫秒
 65         options.maxWaitTime(5000); //
 66         options.socketTimeout(0);// 套接字超時時間,0無限制
 67         options.threadsAllowedToBlockForConnectionMultiplier(5000);// 線程隊列數,如果連接線程排滿了隊列就會拋出“Out of semaphores to get db”錯誤。
 68         options.writeConcern(WriteConcern.SAFE);//
 69         options.build();
 70     }
 71 
 72     // ------------------------------------共用方法---------------------------------------------------
 73     /**
 74      * 獲取DB實例 - 指定DB
 75      * 
 76      * @param dbName
 77      * @return
 78      */
 79     public MongoDatabase getDB(String dbName) {
 80         if (dbName != null && !"".equals(dbName)) {
 81             MongoDatabase database = mongoClient.getDatabase(dbName);
 82             return database;
 83         }
 84         return null;
 85     }
 86 
 87     /**
 88      * 獲取collection對象 - 指定Collection
 89      * 
 90      * @param collName
 91      * @return
 92      */
 93     public MongoCollection<Document> getCollection(String dbName, String collName) {
 94         if (null == collName || "".equals(collName)) {
 95             return null;
 96         }
 97         if (null == dbName || "".equals(dbName)) {
 98             return null;
 99         }
100         MongoCollection<Document> collection = mongoClient.getDatabase(dbName).getCollection(collName);
101         return collection;
102     }
103 
104     /**
105      * 查詢DB下的所有表名
106      */
107     public List<String> getAllCollections(String dbName) {
108         MongoIterable<String> colls = getDB(dbName).listCollectionNames();
109         List<String> _list = new ArrayList<String>();
110         for (String s : colls) {
111             _list.add(s);
112         }
113         return _list;
114     }
115 
116     /**
117      * 獲取所有數據庫名稱列表
118      * 
119      * @return
120      */
121     public MongoIterable<String> getAllDBNames() {
122         MongoIterable<String> s = mongoClient.listDatabaseNames();
123         return s;
124     }
125 
126     /**
127      * 刪除一個數據庫
128      */
129     public void dropDB(String dbName) {
130         getDB(dbName).drop();
131     }
132 
133     /**
134      * 查找對象 - 根據主鍵_id
135      * 
136      * @param collection
137      * @param id
138      * @return
139      */
140     public Document findById(MongoCollection<Document> coll, String id) {
141         ObjectId _idobj = null;
142         try {
143             _idobj = new ObjectId(id);
144         } catch (Exception e) {
145             return null;
146         }
147         Document myDoc = coll.find(Filters.eq("_id", _idobj)).first();
148         return myDoc;
149     }
150 
151     /** 統(tǒng)計數 */
152     public int getCount(MongoCollection<Document> coll) {
153         int count = (int) coll.count();
154         return count;
155     }
156 
157     /** 條件查詢 */
158     public MongoCursor<Document> find(MongoCollection<Document> coll, Bson filter) {
159         return coll.find(filter).iterator();
160     }
161 
162     /** 分頁查詢 */
163     public MongoCursor<Document> findByPage(MongoCollection<Document> coll, Bson filter, int pageNo, int pageSize) {
164         Bson orderBy = new BasicDBObject("_id", 1);
165         return coll.find(filter).sort(orderBy).skip((pageNo - 1) * pageSize).limit(pageSize).iterator();
166     }
167     
168 
169     /**
170      * 通過ID刪除
171      * 
172      * @param coll
173      * @param id
174      * @return
175      */
176     public int deleteById(MongoCollection<Document> coll, String id) {
177         int count = 0;
178         ObjectId _id = null;
179         try {
180             _id = new ObjectId(id);
181         } catch (Exception e) {
182             return 0;
183         }
184         Bson filter = Filters.eq("_id", _id);
185         DeleteResult deleteResult = coll.deleteOne(filter);
186         count = (int) deleteResult.getDeletedCount();
187         return count;
188     }
189 
190     /**
191      * FIXME
192      * 
193      * @param coll
194      * @param id
195      * @param newdoc
196      * @return
197      */
198     public Document updateById(MongoCollection<Document> coll, String id, Document newdoc) {
199         ObjectId _idobj = null;
200         try {
201             _idobj = new ObjectId(id);
202         } catch (Exception e) {
203             return null;
204         }
205         Bson filter = Filters.eq("_id", _idobj);
206         // coll.replaceOne(filter, newdoc); // 完全替代
207         coll.updateOne(filter, new Document("$set", newdoc));
208         return newdoc;
209     }
210 
211     public void dropCollection(String dbName, String collName) {
212         getDB(dbName).getCollection(collName).drop();
213     }
214 
215     /**
216      * 關閉Mongodb
217      */
218     public void close() {
219         if (mongoClient != null) {
220             mongoClient.close();
221             mongoClient = null;
222         }
223     }
224 
225     /**
226      * 測試入口
227      * 
228      * @param args
229      * @throws CloneNotSupportedException 
230      */
231     public static void main(String[] args) {
232         
233         String dbName = "test";
234         String collName = "wd_paper_scie";
235         MongoCollection<Document> coll = MongoUtil.instance.getCollection(dbName, collName);
236         //coll.createIndex(new Document("validata",1));//創(chuàng)建索引
237         //coll.createIndex(new Document("id",1));
238        // coll.createIndex(new Document("ut_wos",1),new IndexOptions().unique(true));//創(chuàng)建唯一索引
239         //coll.dropIndexes();//刪除索引
240         //coll.dropIndex("validata_1");//根據索引名刪除某個索引
241         ListIndexesIterable<Document> list = coll.listIndexes();//查詢所有索引
242         for (Document document : list) {
243             System.out.println(document.toJson());
244         }
245         coll.find(Filters.and(Filters.eq("x", 1), Filters.lt("y", 3)));
246         coll.find(and(eq("x", 1), lt("y", 3)));
247         coll.find().sort(ascending("title"));  
248         coll.find().sort(new Document("id",1)); 
249         coll.find(new Document("$or", Arrays.asList(new Document("owner", "tom"), new Document("words", new Document("$gt", 350)))));
250         coll.find().projection(fields(include("title", "owner"), excludeId()));  
251         // coll.updateMany(Filters.eq("validata", 1), Updates.set("validata", 0));
252         //coll.updateMany(Filters.eq("validata", 1), new Document("$unset", new Document("jigou", "")));//刪除某個字段
253         //coll.updateMany(Filters.eq("validata", 1), new Document("$rename", new Document("affiliation", "affiliation_full")));//修改某個字段名
254         //coll.updateMany(Filters.eq("validata", 1), new Document("$rename", new Document("affiliationMeta", "affiliation")));
255         //coll.updateMany(Filters.eq("validata", 1), new Document("$set", new Document("validata", 0)));//修改字段值
256 //        MongoCursor<Document> cursor1 =coll.find(Filters.eq("ut_wos", "WOS:000382970200003")).iterator();
257 //        while(cursor1.hasNext()){
258 //            Document sd=cursor1.next();
259 //            System.out.println(sd.toJson());
260 //            coll.insertOne(sd);
261 //        }
262        
263 //        MongoCursor<Document> cursor1 =coll.find(Filters.elemMatch("affInfo", Filters.eq("firstorg", 1))).iterator();
264 //        while(cursor1.hasNext()){
265 //            Document sd=cursor1.next();
266 //            System.out.println(sd.toJson());
267 //        }
268         //查詢只返回指定字段
269        // MongoCursor<Document> doc= coll.find().projection(Projections.fields(Projections.include("ut_wos","affiliation"),Projections.excludeId())).iterator();
270         //"ut_wos" : "WOS:000382970200003"
271        //coll.updateMany(Filters.eq("validata", 1), new Document("$set", new Document("validata", 0)));
272         //coll.updateMany(Filters.eq("validata", 0), new Document("$rename", new Document("sid", "ssid")), new UpdateOptions().upsert(false));
273         //coll.updateOne(Filters.eq("ut_wos", "WOS:000382970200003"), new Document("$set", new Document("validata", 0)));
274         //long isd=coll.count(Filters.elemMatch("affInfo", Filters.elemMatch("affiliationJGList", Filters.eq("sid", 0))));
275        // System.out.println(isd);
276         //MongoCursor<Document> doc= coll.find(Filters.elemMatch("affInfo", Filters.elemMatch("affiliationJGList", Filters.ne("sid", 0)))).projection(Projections.fields(Projections.elemMatch("affInfo"),Projections.excludeId())).iterator();
277 //       MongoCursor<Document> doc= coll.find().projection(Projections.include("affInfo","ssid")).iterator();
278 //       while(doc.hasNext()){
279 //            Document sd=doc.next();
280 //            System.out.println(sd.toJson());
281 //            
282 //        }
283         MongoUtil.instance.close();
284         // 插入多條
285 //         for (int i = 1; i <= 4; i++) {
286 //         Document doc = new Document();
287 //         doc.put("name", "zhoulf");
288 //         doc.put("school", "NEFU" + i);
289 //         Document interests = new Document();
290 //         interests.put("game", "game" + i);
291 //         interests.put("ball", "ball" + i);
292 //         doc.put("interests", interests);
293 //         coll.insertOne(doc);
294 //         }
295 //       
296        /* MongoCursor<Document> sd =coll.find().iterator();
297         while(sd.hasNext()){
298             Document doc = sd.next();
299             String id =  doc.get("_id").toString();
300             List<AffiliationJG> list = new ArrayList<AffiliationJG>();
301             AffiliationJG jg = new AffiliationJG();
302             jg.setAddress("123");
303             jg.setCid(2);
304             jg.setCname("eeee");
305             jg.setSid(3);
306             jg.setSname("rrrr");
307             AffiliationJG jg2 = new AffiliationJG();
308             jg2.setAddress("3242");
309             jg2.setCid(2);
310             jg2.setCname("ers");
311             jg2.setSid(3);
312             jg2.setSname("rasdr");
313             list.add(jg);
314             list.add(jg2);
315             AffiliationList af = new AffiliationList();
316             af.setAffiliationAuthos("33333");
317             af.setAffiliationinfo("asdsa");
318             af.setAffiliationJGList(list);
319             JSONObject json = JSONObject.fromObject(af);
320             doc.put("affInfo", json);
321             MongoDBUtil.instance.updateById(coll, id, doc);
322         }*/
323         
324 //        Bson bs = Filters.eq("name", "zhoulf");
325 //        coll.find(bs).iterator();
326         // // 根據ID查詢
327         // String id = "556925f34711371df0ddfd4b";
328         // Document doc = MongoDBUtil2.instance.findById(coll, id);
329         // System.out.println(doc);
330 
331         // 查詢多個
332         // MongoCursor<Document> cursor1 = coll.find(Filters.eq("name", "zhoulf")).iterator();
333         // while (cursor1.hasNext()) {
334         // org.bson.Document _doc = (Document) cursor1.next();
335         // System.out.println(_doc.toString());
336         // }
337         // cursor1.close();
338 
339         // 查詢多個
340 //         MongoCursor<WdPaper> cursor2 = coll.find(WdPaper.class).iterator();
341 //         while(cursor2.hasNext()){
342 //             WdPaper doc = cursor2.next();
343 //             System.out.println(doc.getUt_wos());
344 //         }
345         // 刪除數據庫
346         // MongoDBUtil2.instance.dropDB("testdb");
347 
348         // 刪除表
349         // MongoDBUtil2.instance.dropCollection(dbName, collName);
350 
351         // 修改數據
352         // String id = "556949504711371c60601b5a";
353         // Document newdoc = new Document();
354         // newdoc.put("name", "時候");
355         // MongoDBUtil.instance.updateById(coll, id, newdoc);
356 
357         // 統(tǒng)計表
358          //System.out.println(MongoDBUtil.instance.getCount(coll));
359 
360         // 查詢所有
361 //        Bson filter = Filters.eq("count", 0);
362 //        MongoDBUtil.instance.find(coll, filter);
363 
364     }
365 
366 }  五、 總結mongodb:它是一個內存數據庫,操作的數據都是放在內存里面的。但實際數據存在硬盤中,mmap的方式可以說是索引在內存中。持久化方式:mongodb的所有數據實際上是存放在硬盤的,所有要操作的數據通過mmap的方式映射到內存某個區(qū)域內。mongodb就在這塊區(qū)域里面進行數據修改,避免了零碎的硬盤操作。至于mmap上的內容flush到硬盤就是操作系統(tǒng)的事情了,所以如果mongodb在內存中修改了數據后,mmap數據flush到硬盤之前,系統(tǒng)宕機了,數據就會丟失。 redis:它就是一個不折不扣的內存數據庫了。持久化方式:redis所有數據都是放在內存中的,持久化是使用RDB方式或者aof方式。 mysql:無論數據還是索引都存放在硬盤中。到要使用的時候才交換到內存中。能夠處理遠超過內存總量的數據。 數據量和性能:當物理內存夠用的時候,redis>mongodb>mysql當物理內存不夠用的時候,redis和mongodb都會使用虛擬內存。mysql>mongodb>redis redis要開始虛擬內存,那很明顯要么加內存條,要么你換個數據庫了。mongodb不一樣,只要,業(yè)務上能保證,冷熱數據的讀寫比,使得熱數據在物理內存中,mmap的交換較少。mongodb還是能夠保證性能。有人使用mongodb存儲了上T的數據。mysql根本就不需要擔心數據量跟內存下的關系。不過,內存的量跟熱數據的關系會極大地影響性能表現。 總結就是虛擬內存不夠是 選擇mongodb和mysql虛擬內存夠是 選擇mongodb和redis

看完上述內容,你們對mongodb中如何安裝java有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細節(jié)
推薦閱讀:
  1. mongodb 安裝
  2. 安裝MongoDB

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI