mongodb中如何安装java

发布时间:2021-07-30 15:55:05 作者:Leah
来源:亿速云 阅读:99

今天就跟大家聊聊有关mongodb中如何安装java,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

一、 安装

mongodb中如何安装java

环境变量设置

mongodb中如何安装java

mongodb中如何安装java

创建数据目录,data文件夹,conf文件夹,db文件夹,log文件夹

mongodb中如何安装java

mongodb中如何安装java

创建配置文件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

创建用户

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  
    // 这里还有几个角色间接或直接提供了系统超级用户的访问(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     /** 统计数 */
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));//创建索引
237         //coll.createIndex(new Document("id",1));
238        // coll.createIndex(new Document("ut_wos",1),new IndexOptions().unique(true));//创建唯一索引
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         // 统计表
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的方式映射到内存某个区域内。mongodb就在这块区域里面进行数据修改,避免了零碎的硬盘操作。至于mmap上的内容flush到硬盘就是操作系统的事情了,所以如果mongodb在内存中修改了数据后,mmap数据flush到硬盘之前,系统宕机了,数据就会丢失。 redis:它就是一个不折不扣的内存数据库了。持久化方式:redis所有数据都是放在内存中的,持久化是使用RDB方式或者aof方式。 mysql:无论数据还是索引都存放在硬盘中。到要使用的时候才交换到内存中。能够处理远超过内存总量的数据。 数据量和性能:当物理内存够用的时候,redis>mongodb>mysql当物理内存不够用的时候,redis和mongodb都会使用虚拟内存。mysql>mongodb>redis redis要开始虚拟内存,那很明显要么加内存条,要么你换个数据库了。mongodb不一样,只要,业务上能保证,冷热数据的读写比,使得热数据在物理内存中,mmap的交换较少。mongodb还是能够保证性能。有人使用mongodb存储了上T的数据。mysql根本就不需要担心数据量跟内存下的关系。不过,内存的量跟热数据的关系会极大地影响性能表现。 总结就是虚拟内存不够是 选择mongodb和mysql虚拟内存够是 选择mongodb和redis

看完上述内容,你们对mongodb中如何安装java有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

推荐阅读:
  1. mongodb 安装
  2. 安装MongoDB

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

mongodb java

上一篇:怎么用css3实现竖形二级导航

下一篇:mac中如何安装kafka

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》