码迷,mamicode.com
首页 > 数据库 > 详细

mongodb ----> 从入门到。。。

时间:2018-09-05 11:12:28      阅读:275      评论:0      收藏:0      [点我收藏+]

标签:extc   conf   .com   lte   1.0   spirng   rop   sel   存储   

环境:

centos6.8,jdk1.8.0_u172,mongodb-4.0.0,spring boot-1.5.15

1、环境搭建

 1 tar -zxvf mongodb-linux-x86_64-rhel62-4.0.0.tgz -C /home/rui/ #解压,指定放置位置
 2 
 3 mv mongodb-linux-x86_64-rhel62-4.0.0 mongodb-4.0.0 #重命名
 4 
 5 cd mongodb-4.0.0 
 6 
 7 vim mongodb.conf  #配置数据库db和日志log
 8      dbpath=/home/rui/mongodb-4.0.0/data/db
 9      logpath=/home/rui/mongodb-4.0.0/data/log
10 
11 mkdir -p data/db #创建目录
12 mkdir -p data/log
13
14 vim /etc/profile #添加环境变量
15 export PATH=$PATH:/home/rui/mongodb-4.0.0/bin
16 source /etc/profile
17

验证mongodb安装是否正确:

1 mongo -version

技术分享图片

启动mongodb:

1 mongod --config /home/rui/mongodb-4.0.0/mongodb.config 

技术分享图片

启动mongodb shell:

1 mongo

技术分享图片

2、概念

基础概念:文档、集合、数据库

英文对应:document, collection, database

其他概念:字段、索引、主键

英文对应:field, index, primary key  

BSON(Binary JSON):类似json的二进制形式的存储格式

3、常用命令

1 1、显示所有数据库
2 show dbs
3 
4 2、显示当前数据库
5 db
6 
7 3、指定使用某数据库,当数据库xxx不存在时,该指令会创建数据库xxx
8 use xxx
9
10 4、删除数据库
11 use xxx
12 db.dropDatabase()
13 ===========================================================================
14 5、创建集合
15 use xxx
16 db.createCollection("collectionName")或者 db.createCollection("collectionName", options)
16 #options指定参数:capped,autoIndex,size,max
17
18 6、显示集合
19 show collections
20
21 7、删除集合
22 db.collectionName.drop()
23 =============================================================================
24 8、插入文档
24 (集合中存储的数据都是BSON格式;每个文档有默认的主键_id,默认的数据类型是ObjectId,可以任何其他数据类型)
25 db.collectionName.insert(document)#_id相同时,新增失败
26 db.collectionName.save(document) #_id相同时,新增会覆盖文档
27
28 9、查询文档
29 db.collectionName.find(<query>,<projection>)
29 #返回满足条件的所有文档,query指定查询条件 projection指定返回的字段
30 db.collectionName.find()#返回所有文档
31 db.collectionName.findOne()#返回一条文档
32
33 10、更新文档
34 db.collectionName.update(<query>,<update>,{upsert:<boolean>,muti:<boolean>})
34 #query指定查询条件 update需要更新的对象
35
36 11、删除文档
37 db.collectionName.remove(<query>,{justOne:<boolean>})
38
39 12、显示指定数量的文档
40 db.collectionName.find().limit(number)
41
42 13、跳过指定数量的文档
43 db.collectionName.find().limit(number1).skip(number2)
44 db.collectionName.find().skip(number1).limit(number2)#可以实现分页


4、java操作mongodb

maven依赖:

1 <dependency>
2         <groupId>org.mongodb</groupId>
3         <artifactId>mongo-java-driver</artifactId>
4         <version>3.8.1</version>
5  </dependency>

连接mongodb,crud等测试,完整代码:

技术分享图片
  1 package com.rui;
  2 
  3 
  4 import org.junit.Test;
  5 import org.junit.Before;
  6 import org.junit.runner.RunWith;
  7 import org.springframework.test.context.ContextConfiguration;
  8 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  9 
 10 
 11 //common
 12 import com.mongodb.client.MongoDatabase;
 13 import com.mongodb.client.MongoCollection;
 14 
 15 import org.bson.Document;
 16 import java.util.Arrays;
 17 import com.mongodb.Block;
 18 
 19 import com.mongodb.client.MongoCursor;
 20 import static com.mongodb.client.model.Filters.*;
 21 import com.mongodb.client.result.DeleteResult;
 22 import static com.mongodb.client.model.Updates.*;
 23 import com.mongodb.client.result.UpdateResult;
 24 import java.util.ArrayList;
 25 import java.util.List;
 26 
 27 //new
 28 import com.mongodb.ConnectionString;
 29 import com.mongodb.client.MongoClients;
 30 import com.mongodb.client.MongoClient;
 31 import com.mongodb.client.MongoIterable;
 32 import com.mongodb.MongoClientSettings;
 33 import com.mongodb.ServerAddress;
 34 
 35 @RunWith(SpringJUnit4ClassRunner.class)
 36 @ContextConfiguration(locations={"classpath*:spring-mongodb.xml"})
 37 public class NewMongodbConnTest{
 38     
 39     
 40     private MongoDatabase database = null;
 41     @Before
 42     //@Test
 43     public void ConnTest(){
 44         
 45         //default port = 27017 hostname = localhost
 46         //MongoClient mongoClient = MongoClients.create();
 47         
 48         //or self define port and hostname
 49         MongoClient mongoClient = MongoClients.create(
 50         MongoClientSettings.builder()
 51                 .applyToClusterSettings(builder ->
 52                   builder.hosts(Arrays.asList(new ServerAddress("192.168.0.102", 27017))))
 53                 .build());
 54                 
 55         // access a Database
 56          database = mongoClient.getDatabase("rui");
 57         
 58         // print all collection name in database
 59          MongoIterable<String> iterable = database.listCollectionNames();
 60          MongoCursor<String> cursor = iterable.iterator();
 61          try{
 62              while(cursor.hasNext()){
 63                  System.out.println(cursor.next());
 64              }
 65          }finally{
 66              cursor.close();
 67          }
 68          
 69         
 70     }
 71     
 72     @Test
 73     public void crudTest(){
 74         
 75         // access a Collection
 76         MongoCollection<Document> collection = database.getCollection("rui");
 77         
 78         // create a Document
 79         Document doc = new Document("name", "MongoDB")
 80                 .append("type", "database")
 81                 .append("count", 1)
 82                 .append("versions", Arrays.asList("v3.2", "v3.0", "v2.6"))
 83                 .append("info", new Document("x", 203).append("y", 102)); 
 84                 
 85                 
 86         // insert one Document
 87          collection.insertOne(doc);
 88          
 89         // insert many Document
 90         List<Document> documents = new ArrayList<Document>();
 91         for (int i = 0; i < 100; i++) {
 92              documents.add(new Document("i", i));
 93         }
 94          collection.insertMany(documents); 
 95          
 96         // count Document in collection
 97          System.out.println("document counts: " + collection.countDocuments());
 98         
 99         
100         // query first Document
101          Document myDoc = collection.find().first();
102          System.out.println(myDoc.toJson()); 
103          
104         //find all Document
105         MongoCursor<Document> cursor = collection.find().iterator();
106         try {
107             while (cursor.hasNext()) {
108                 System.out.println(cursor.next().toJson());
109             }
110         } finally {
111             cursor.close();
112         } 
113         
114         //query one by a filter,pay attention to Filters helper
115          Document myDoc = collection.find(eq("i", 71)).first();
116          System.out.println(myDoc.toJson()); 
117         
118         
119         // query all by a filter,pay attention to Filters helper
120         Block<Document> printBlock = new Block<Document>() {
121              @Override
122              public void apply(final Document document) {
123                  System.out.println(document.toJson());
124              }
125          };
126 
127          collection.find(gt("i", 50)).forEach(printBlock); 
128          
129         //update one Document
130          collection.updateOne(eq("i", 10), new Document("$set", new Document("i", 110)));
131          
132         //update muti
133          UpdateResult updateResult = collection.updateMany(lt("i", 100), inc("i", 100));
134          System.out.println(updateResult.getModifiedCount()); 
135          
136         // delete one Document
137         // collection.deleteOne(eq("i", 110));
138          
139         // delete muti
140          DeleteResult deleteResult = collection.deleteMany(gte("i", 100));
141          System.out.println(deleteResult.getDeletedCount()); 
142          
143         // create index
144          collection.createIndex(new Document("i", 1));
145     
146     }
147 }
View Code

windows连接linux中的mongodb,启动MongoDB方式如下:

技术分享图片

各个代码块测试结果截图:

1、连接测试:

技术分享图片

技术分享图片

2、插入一条文档:

技术分享图片

3、插入多条文档:

技术分享图片

4、计算总文档条数:

技术分享图片

5、查询第一条文档:

技术分享图片

6、查询所有文档:

技术分享图片

7、通过filter查询某条文档:

技术分享图片

8、通过filter查询多条文档:

技术分享图片

9、更新一条文档:

技术分享图片

10、更新多条文档:

技术分享图片

11、删除一条文档:

技术分享图片

12、删除多条文档:

技术分享图片

PojoMongodbTest.java

技术分享图片
  1 package com.rui;
  2 
  3 import org.junit.Test;
  4 import org.junit.runner.RunWith;
  5 import org.springframework.test.context.ContextConfiguration;
  6 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  7 
  8 import org.bson.Document;
  9 import com.mongodb.Block;
 10 //import com.mongodb.MongoClient;
 11 import com.mongodb.MongoClientURI;
 12 import com.mongodb.client.MongoCollection;
 13 import com.mongodb.client.MongoDatabase;
 14 import com.mongodb.client.result.DeleteResult;
 15 import com.mongodb.client.result.UpdateResult;
 16 import org.bson.codecs.configuration.CodecRegistry;
 17 import org.bson.codecs.pojo.PojoCodecProvider;
 18 import com.mongodb.client.MongoClients;
 19 //import com.mongodb.client.MongoClient;
 20 
 21 import java.util.List;
 22 
 23 import static com.mongodb.client.model.Filters.*;
 24 import static com.mongodb.client.model.Updates.*;
 25 import java.util.Arrays;
 26 import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
 27 import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
 28 import com.mongodb.MongoClientSettings;
 29 import com.mongodb.ServerAddress;
 30 
 31 //@RunWith(SpringJUnit4ClassRunner.class)
 32 //@ContextConfiguration(locations={"classpath*:spring-mongodb.xml"})
 33 public class PojoMongodbTest{
 34     
 35    @Test
 36    public void pojoTest(){
 37        
 38      CodecRegistry pojoCodecRegistry = fromRegistries(com.mongodb.MongoClient.getDefaultCodecRegistry(),
 39                 fromProviders(PojoCodecProvider.builder().automatic(true).build()));
 40                 
 41                 
 42      /*MongoClientSettings settings = MongoClientSettings.builder()
 43         .codecRegistry(pojoCodecRegistry)
 44         .build();
 45      MongoClient mongoClient = MongoClients.create(settings); */
 46      
 47      com.mongodb.client.MongoClient mongoClient = MongoClients.create(
 48         MongoClientSettings.builder()
 49                 .codecRegistry(pojoCodecRegistry)  // codec
 50                 .applyToClusterSettings(builder ->
 51                   builder.hosts(Arrays.asList(new ServerAddress("192.168.0.102", 27017))))
 52                 .build());
 53      
 54      MongoDatabase database = mongoClient.getDatabase("rui");
 55     
 56      MongoCollection<Person> collection = database.getCollection("people", Person.class);
 57     
 58      //Insert a Person
 59      Person ada = new Person("Ada Byron", 20, new Address("St James Square", "London", "W1"));
 60      collection.insertOne(ada);
 61      
 62      //Insert multi Persons
 63      List<Person> people = java.util.Arrays.asList(
 64         new Person("Charles Babbage", 45, new Address("5 Devonshire Street", "London", "W11")),
 65         new Person("Alan Turing", 28, new Address("Bletchley Hall", "Bletchley Park", "MK12")),
 66         new Person("Timothy Berners-Lee", 61, new Address("Colehill", "Wimborne", null))
 67      );
 68      collection.insertMany(people); 
 69      
 70      //query the collection
 71     Block<Person> printBlock = new Block<Person>() {
 72          @Override
 73          public void apply(final Person person) {
 74             System.out.println(person);
 75          }
 76      };
 77      collection.find().forEach(printBlock); 
 78      
 79      //query one by specifying query Filter
 80     Person somebody = collection.find(eq("address.city", "Wimborne")).first();
 81      System.out.println(somebody.toString()); 
 82      
 83      //query all by specifying query Filter
 84      collection.find(gt("age", 30)).forEach(printBlock);
 85      
 86      //update one
 87      collection.updateOne(eq("name", "Ada Byron"), combine(set("age", 23), set("name", "Ada Lovelace")));
 88      
 89      //update multi ??? 原来文档少了“address.”!!!
 90      UpdateResult updateResult = collection.updateMany(not(eq("address.zip", null)), set("address.zip", null));
 91      System.out.println(updateResult.getModifiedCount()); 
 92      
 93      //replace 
 94     Person ada = new Person("Ada Byron", 20, new Address("St James Square", "London", "W1"));
 95      collection.replaceOne(eq("name", "Ada Lovelace"), ada);
 96      
 97      //delete one
 98     // collection.deleteOne(eq("address.city", "Wimborne"));
 99      
100      //delete multi
101      DeleteResult deleteResult = collection.deleteMany(eq("address.city", "London"));
102      System.out.println(deleteResult.getDeletedCount()); 
103      
104      }
105 }
View Code

 Person.java

技术分享图片
 1 package com.rui;
 2 
 3 import lombok.Setter;
 4 import lombok.Getter;
 5 import lombok.ToString;
 6 import lombok.NoArgsConstructor;
 7 import org.bson.types.ObjectId;
 8 
 9 @Setter
10 @Getter
11 @NoArgsConstructor
12 @ToString
13 public final class Person{
14     
15     private ObjectId id;
16     private String name;
17     private int age;
18     private Address address;
19     
20     //public Person(){}
21     
22     public Person(String name, int age, Address address){
23         this.name = name;
24         this.age = age;
25         this.address = address;
26     }
27 }
View Code

Address.java

技术分享图片
 1 package com.rui;
 2 
 3 import lombok.Setter;
 4 import lombok.Getter;
 5 import lombok.ToString;
 6 import lombok.AllArgsConstructor;
 7 import lombok.NoArgsConstructor;
 8 
 9 @Setter
10 @Getter
11 @AllArgsConstructor
12 @NoArgsConstructor
13 @ToString
14 public final class Address{
15     
16     private String street;
17     private String city;
18     private String zip;
19 }
View Code

1、插入一个person

技术分享图片

2、插入多个person

技术分享图片

3、查询全部person

技术分享图片

4、查询满足个条件(Filter)的一个person

技术分享图片

5、查询满足某个条件(Filter)的多个persons

技术分享图片

6、更新满足个条件(Filter)的一个person

技术分享图片

7、更新满足个条件(Filter)的多个person,可以通过UpdateResult类返回更新信息(官方文档的update示例有错误,少了“address.”

技术分享图片

技术分享图片

 

8、替代满足个条件(Filter)的person

技术分享图片

9、删除满足个条件(Filter)的一个person

技术分享图片

10、删除满足个条件(Filter)的多个person,可以通过DeleteResult类返回删除信息

技术分享图片

技术分享图片

5、spring整合mongodb

1)maven依赖

 1    <dependency>
 2             <groupId>org.mongodb</groupId>
 3             <artifactId>mongo-java-driver</artifactId>
 4             <version>3.1.0</version>
 5    </dependency>
 6 
 7     <dependency>
 8             <groupId>org.springframework.data</groupId>
 9             <artifactId>spring-data-mongodb</artifactId>
10             <version>1.8.0.RELEASE</version>
11     </dependency>

2)spring-mongodb.xml配置

技术分享图片
 1 <context:property-placeholder location="classpath:/com/myapp/mongodb/config/mongo.properties"/>
 2 
 3 <mongo:mongo-client host="${mongo.host}" port="${mongo.port}">
 4   <mongo:client-options
 5      connections-per-host="${mongo.connectionsPerHost}"
 6      threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
 7      connect-timeout="${mongo.connectTimeout}"
 8      max-wait-time="${mongo.maxWaitTime}"
 9      auto-connect-retry="${mongo.autoConnectRetry}"
10      socket-keep-alive="${mongo.socketKeepAlive}"
11      socket-timeout="${mongo.socketTimeout}"
12      slave-ok="${mongo.slaveOk}"
13      write-number="1"
14      write-timeout="0"
15      write-fsync="true"/>
16 </mongo:mongo-client>
17 
18 <mongo:db-factory dbname="database" mongo-ref="mongoClient"/>
19 
20 <bean id="anotherMongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
21   <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
22 </bean>
View Code

6、spring boot整合mongodb

1)maven依赖

1 <dependency>
2      <groupId>org.springframework.boot</groupId>
3      <artifactId>spring-boot-starter-data-mongodb</artifactId>
4  </dependency>

2)application.properties配置

1 spring.application.name=spirng-boot-mongodb
2 
3 spring.data.mongodb.uri=mongodb://127.0.0.1:27017/rui

3)关注spring-data-mongodb的一个重要的类,提供了很多个实用的crud方法

1 org.springframework.data.mongodb.core.MongoTemplate; 

template是高度抽象的类,用来存储和查询文档。

 

参考资料:

https://mongodb.github.io/mongo-java-driver/3.8/driver/getting-started/quick-start/

https://mongodb.github.io/mongo-java-driver/3.8/driver/getting-started/quick-start-pojo/

https://docs.spring.io/spring-data/mongodb/docs/2.0.9.RELEASE/reference/html/

mongodb ----> 从入门到。。。

标签:extc   conf   .com   lte   1.0   spirng   rop   sel   存储   

原文地址:https://www.cnblogs.com/mrray1105/p/9555695.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!