环境:
centos6.8,jdk1.8.0_u172,mongodb-4.0.0,spring boot-1.5.15
1、环境搭建
tar -zxvf mongodb-linux-x86_64-rhel62-4.0.0.tgz -C /home/rui/ #解压,指定放置位置 mv mongodb-linux-x86_64-rhel62-4.0.0 mongodb-4.0.0 #重命名 cd mongodb-4.0.0 vim mongodb.conf #配置数据库db和日志log dbpath=/home/rui/mongodb-4.0.0/data/db logpath=/home/rui/mongodb-4.0.0/data/log mkdir -p data/db #创建目录 mkdir -p data/log13 14 vim /etc/profile #添加环境变量15 export PATH=$PATH:/home/rui/mongodb-4.0.0/bin16 source /etc/profile17
验证mongodb安装是否正确:
mongo -version
启动mongodb:
mongod --config /home/rui/mongodb-4.0.0/mongodb.config
启动mongodb shell:
mongo
2、概念
基础概念:文档、集合、数据库
英文对应:document, collection, database
其他概念:字段、索引、主键
英文对应:field, index, primary key
BSON(Binary JSON):类似json的二进制形式的存储格式
3、常用命令
1、显示所有数据库 show dbs 2、显示当前数据库 db 3、指定使用某数据库,当数据库xxx不存在时,该指令会创建数据库xxx use xxx910 4、删除数据库11 use xxx12 db.dropDatabase()13 ===========================================================================14 5、创建集合15 use xxx16 db.createCollection("collectionName")或者 db.createCollection("collectionName", options)16 #options指定参数:capped,autoIndex,size,max1718 6、显示集合19 show collections2021 7、删除集合22 db.collectionName.drop()23 =============================================================================24 8、插入文档 24 (集合中存储的数据都是 28 9、查询文档29 db.collectionName.find(<query>,<projection>)29 #返回满足条件的所有文档,query指定查询条件 projection指定返回的字段30 db.collectionName.find()#返回所有文档31 db.collectionName.findOne()#返回一条文档3233 10、更新文档34 db.collectionName.update(<query>,<update>,{upsert:<boolean>,muti:<boolean>})34 #query指定查询条件 update需要更新的对象3536 11、删除文档37 db.collectionName.remove(<query>,{justOne:<boolean>})3839 12、显示指定数量的文档40 db.collectionName.find().limit(number)4142 13、跳过指定数量的文档43 db.collectionName.find().limit(number1).skip(number2)44 db.collectionName.find().skip(number1).limit(number2)#可以实现分页
4、java操作mongodb
maven依赖:
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.8.1</version> </dependency>
连接mongodb,crud等测试,完整代码:
package com.rui; import org.junit.Test; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; //common import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoCollection; import org.bson.Document; import java.util.Arrays; import com.mongodb.Block; import com.mongodb.client.MongoCursor; import static com.mongodb.client.model.Filters.*; import com.mongodb.client.result.DeleteResult; import static com.mongodb.client.model.Updates.*; import com.mongodb.client.result.UpdateResult; import java.util.ArrayList; import java.util.List; //new import com.mongodb.ConnectionString; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoIterable; import com.mongodb.MongoClientSettings; import com.mongodb.ServerAddress; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath*:spring-mongodb.xml"}) public class NewMongodbConnTest{ private MongoDatabase database = null; @Before //@Test public void ConnTest(){ //default port = 27017 hostname = localhost //MongoClient mongoClient = MongoClients.create(); //or self define port and hostname MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder() .applyToClusterSettings(builder -> builder.hosts(Arrays.asList(new ServerAddress("192.168.0.102", 27017)))) .build()); // access a Database database = mongoClient.getDatabase("rui"); // print all collection name in database MongoIterable<String> iterable = database.listCollectionNames(); MongoCursor<String> cursor = iterable.iterator(); try{ while(cursor.hasNext()){ System.out.println(cursor.next()); } }finally{ cursor.close(); } } @Test public void crudTest(){ // access a Collection MongoCollection<Document> collection = database.getCollection("rui"); // create a Document Document doc = new Document("name", "MongoDB") .append("type", "database") .append("count", 1) .append("versions", Arrays.asList("v3.2", "v3.0", "v2.6")) .append("info", new Document("x", 203).append("y", 102)); // insert one Document collection.insertOne(doc); // insert many Document List<Document> documents = new ArrayList<Document>(); for (int i = 0; i < 100; i++) { documents.add(new Document("i", i)); } collection.insertMany(documents); // count Document in collection System.out.println("document counts: " + collection.countDocuments()); // query first Document Document myDoc = collection.find().first(); System.out.println(myDoc.toJson()); //find all Document MongoCursor<Document> cursor = collection.find().iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } //query one by a filter,pay attention to Filters helper Document myDoc = collection.find(eq("i", 71)).first(); System.out.println(myDoc.toJson()); // query all by a filter,pay attention to Filters helper Block<Document> printBlock = new Block<Document>() { @Override public void apply(final Document document) { System.out.println(document.toJson()); } }; collection.find(gt("i", 50)).forEach(printBlock); //update one Document collection.updateOne(eq("i", 10), new Document("$set", new Document("i", 110))); //update muti UpdateResult updateResult = collection.updateMany(lt("i", 100), inc("i", 100)); System.out.println(updateResult.getModifiedCount()); // delete one Document // collection.deleteOne(eq("i", 110)); // delete muti DeleteResult deleteResult = collection.deleteMany(gte("i", 100)); System.out.println(deleteResult.getDeletedCount()); // create index collection.createIndex(new Document("i", 1)); } }
windows连接linux中的mongodb,启动MongoDB方式如下:
各个代码块测试结果截图:
1、连接测试:
2、插入一条文档:
3、插入多条文档:
4、计算总文档条数:
5、查询第一条文档:
6、查询所有文档:
7、通过filter查询某条文档:
8、通过filter查询多条文档:
9、更新一条文档:
10、更新多条文档:
11、删除一条文档:
12、删除多条文档:
PojoMongodbTest.java
package com.rui; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.bson.Document; import com.mongodb.Block; //import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.UpdateResult; import org.bson.codecs.configuration.CodecRegistry; import org.bson.codecs.pojo.PojoCodecProvider; import com.mongodb.client.MongoClients; //import com.mongodb.client.MongoClient; import java.util.List; import static com.mongodb.client.model.Filters.*; import static com.mongodb.client.model.Updates.*; import java.util.Arrays; import static org.bson.codecs.configuration.CodecRegistries.fromProviders; import static org.bson.codecs.configuration.CodecRegistries.fromRegistries; import com.mongodb.MongoClientSettings; import com.mongodb.ServerAddress; //@RunWith(SpringJUnit4ClassRunner.class) //@ContextConfiguration(locations={"classpath*:spring-mongodb.xml"}) public class PojoMongodbTest{ @Test public void pojoTest(){ CodecRegistry pojoCodecRegistry = fromRegistries(com.mongodb.MongoClient.getDefaultCodecRegistry(), fromProviders(PojoCodecProvider.builder().automatic(true).build())); /*MongoClientSettings settings = MongoClientSettings.builder() .codecRegistry(pojoCodecRegistry) .build(); MongoClient mongoClient = MongoClients.create(settings); */ com.mongodb.client.MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder() .codecRegistry(pojoCodecRegistry) // codec .applyToClusterSettings(builder -> builder.hosts(Arrays.asList(new ServerAddress("192.168.0.102", 27017)))) .build()); MongoDatabase database = mongoClient.getDatabase("rui"); MongoCollection<Person> collection = database.getCollection("people", Person.class); //Insert a Person Person ada = new Person("Ada Byron", 20, new Address("St James Square", "London", "W1")); collection.insertOne(ada); //Insert multi Persons List<Person> people = java.util.Arrays.asList( new Person("Charles Babbage", 45, new Address("5 Devonshire Street", "London", "W11")), new Person("Alan Turing", 28, new Address("Bletchley Hall", "Bletchley Park", "MK12")), new Person("Timothy Berners-Lee", 61, new Address("Colehill", "Wimborne", null)) ); collection.insertMany(people); //query the collection Block<Person> printBlock = new Block<Person>() { @Override public void apply(final Person person) { System.out.println(person); } }; collection.find().forEach(printBlock); //query one by specifying query Filter Person somebody = collection.find(eq("address.city", "Wimborne")).first(); System.out.println(somebody.toString()); //query all by specifying query Filter collection.find(gt("age", 30)).forEach(printBlock); //update one collection.updateOne(eq("name", "Ada Byron"), combine(set("age", 23), set("name", "Ada Lovelace"))); //update multi ??? 原来文档少了“address.”!!! UpdateResult updateResult = collection.updateMany(not(eq("address.zip", null)), set("address.zip", null)); System.out.println(updateResult.getModifiedCount()); //replace Person ada = new Person("Ada Byron", 20, new Address("St James Square", "London", "W1")); collection.replaceOne(eq("name", "Ada Lovelace"), ada); //delete one // collection.deleteOne(eq("address.city", "Wimborne")); //delete multi DeleteResult deleteResult = collection.deleteMany(eq("address.city", "London")); System.out.println(deleteResult.getDeletedCount()); } }
Person.java
package com.rui; import lombok.Setter; import lombok.Getter; import lombok.ToString; import lombok.NoArgsConstructor; import org.bson.types.ObjectId; @Setter @Getter @NoArgsConstructor @ToString public final class Person{ private ObjectId id; private String name; private int age; private Address address; //public Person(){} public Person(String name, int age, Address address){ this.name = name; this.age = age; this.address = address; } }
Address.java
package com.rui; import lombok.Setter; import lombok.Getter; import lombok.ToString; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; @Setter @Getter @AllArgsConstructor @NoArgsConstructor @ToString public final class Address{ private String street; private String city; private String zip; }
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依赖
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>1.8.0.RELEASE</version> </dependency>
2)spring-mongodb.xml配置
<context:property-placeholder location="classpath:/com/myapp/mongodb/config/mongo.properties"/> <mongo:mongo-client host="${mongo.host}" port="${mongo.port}"> <mongo:client-options connections-per-host="${mongo.connectionsPerHost}" threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}" connect-timeout="${mongo.connectTimeout}" max-wait-time="${mongo.maxWaitTime}" auto-connect-retry="${mongo.autoConnectRetry}" socket-keep-alive="${mongo.socketKeepAlive}" socket-timeout="${mongo.socketTimeout}" slave-ok="${mongo.slaveOk}" write-number="1" write-timeout="0" write-fsync="true"/> </mongo:mongo-client> <mongo:db-factory dbname="database" mongo-ref="mongoClient"/> <bean id="anotherMongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/> </bean>
6、spring boot整合mongodb
1)maven依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
2)application.properties配置
spring.application.name=spirng-boot-mongodb spring.data.mongodb.uri=mongodb://127.0.0.1:27017/rui
3)关注spring-data-mongodb的一个重要的类,提供了很多个实用的crud方法
org.springframework.data.mongodb.core.MongoTemplate;
template是高度抽象的类,用来存储和查询文档。
7、集群。。。
8、源码。。。
参考资料:
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/