├── src ├── main │ ├── java │ │ └── org │ │ │ └── springframework │ │ │ └── data │ │ │ └── mongodb │ │ │ ├── dao │ │ │ ├── OrderOperations.java │ │ │ ├── impl │ │ │ │ └── OrderRepositoryImpl.java │ │ │ └── OrderRepository.java │ │ │ ├── entity │ │ │ ├── Item.java │ │ │ └── Order.java │ │ │ └── config │ │ │ └── MongoConfig.java │ └── resources │ │ ├── mongo.properties │ │ ├── log4j.xml │ │ └── applicationContext.xml └── test │ └── java │ └── org │ └── springframework │ └── data │ └── mongodb │ ├── Test01.java │ ├── Test04.java │ ├── Test02.java │ └── Test03.java └── pom.xml /src/main/java/org/springframework/data/mongodb/dao/OrderOperations.java: -------------------------------------------------------------------------------- 1 | package org.springframework.data.mongodb.dao; 2 | 3 | import org.springframework.data.mongodb.entity.Order; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * Created by XiuYin.Cui on 2018/3/4. 9 | */ 10 | public interface OrderOperations { 11 | 12 | List findOrdersByType(String t); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/mongodb/dao/impl/OrderRepositoryImpl.java: -------------------------------------------------------------------------------- 1 | package org.springframework.data.mongodb.dao.impl; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.data.mongodb.core.MongoOperations; 5 | import org.springframework.data.mongodb.core.query.Criteria; 6 | import org.springframework.data.mongodb.core.query.Query; 7 | import org.springframework.data.mongodb.entity.Order; 8 | import org.springframework.data.mongodb.dao.OrderOperations; 9 | 10 | import java.util.List; 11 | 12 | /** 13 | * Created by XiuYin.Cui on 2018/3/4. 14 | */ 15 | public class OrderRepositoryImpl implements OrderOperations { 16 | 17 | @Autowired 18 | private MongoOperations mongoOperations; 19 | 20 | 21 | public List findOrdersByType(String t) { 22 | Query type = Query.query(Criteria.where("type").is(t)); 23 | List orders = mongoOperations.find(type, Order.class); 24 | if (orders != null && orders.size()!=0){ 25 | return orders; 26 | } 27 | return null; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/mongodb/entity/Item.java: -------------------------------------------------------------------------------- 1 | package org.springframework.data.mongodb.entity; 2 | 3 | /** 4 | * Created by XiuYin.Cui on 2018/3/1. 5 | */ 6 | public class Item { 7 | 8 | private Long id; 9 | private Order order; 10 | private String product; 11 | private double price; 12 | private int quantity; 13 | 14 | public Long getId() { 15 | return id; 16 | } 17 | 18 | public void setId(Long id) { 19 | this.id = id; 20 | } 21 | 22 | public Order getOrder() { 23 | return order; 24 | } 25 | 26 | public void setOrder(Order order) { 27 | this.order = order; 28 | } 29 | 30 | public String getProduct() { 31 | return product; 32 | } 33 | 34 | public void setProduct(String product) { 35 | this.product = product; 36 | } 37 | 38 | public double getPrice() { 39 | return price; 40 | } 41 | 42 | public void setPrice(double price) { 43 | this.price = price; 44 | } 45 | 46 | public int getQuantity() { 47 | return quantity; 48 | } 49 | 50 | public void setQuantity(int quantity) { 51 | this.quantity = quantity; 52 | } 53 | 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/mongodb/dao/OrderRepository.java: -------------------------------------------------------------------------------- 1 | package org.springframework.data.mongodb.dao; 2 | 3 | import org.springframework.data.mongodb.entity.Order; 4 | import org.springframework.data.mongodb.repository.MongoRepository; 5 | import org.springframework.data.mongodb.repository.Query; 6 | 7 | import java.util.List; 8 | 9 | /** 10 | * Created by XiuYin.Cui on 2018/3/4. 11 | */ 12 | public interface OrderRepository extends MongoRepository,OrderOperations { 13 | /** 14 | * 根据customer从文档中获取Order集合 15 | * @param customer 16 | * @return 17 | */ 18 | //@Query会接受一个JSON查询,而不是JPA查询。?0 表示第一个参数,?1 表示第二个参数,以此类推 19 | // find这个查询动词并不是固定的。如果喜欢的话,我们还可以使用get作为查询动词: 20 | @Query("{'customer':?0,'type':'type'}") 21 | List findByCustomer(String customer); 22 | 23 | /** 24 | * 根据customer 和 type 从文档中获取Order集合 25 | * @param customer 26 | * @param type 27 | * @return 28 | */ 29 | List findByCustomerAndType(String customer, String type); 30 | 31 | /** 32 | * 根据customer 和 type 从文档中获取Order集合(customer 在对比的时候使用的是like 而不是equals) 33 | * @param customer 34 | * @param type 35 | * @return 36 | */ 37 | List findByCustomerLikeAndTypeLike(String customer, String type); 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/resources/mongo.properties: -------------------------------------------------------------------------------- 1 | mongo.host = 127.0.0.1 2 | mongo.port = 27017 3 | mongo.database = admin 4 | mongo.user = root 5 | mongo.password = root 6 | 7 | mongo.minConnectionsPerHost=5 8 | mongo.maxConnectionIdleTime=1500 9 | mongo.maxConnectionLifeTime=0 10 | #mongo slave 11 | mongo.heartbeatSocketTimeout=1000 12 | mongo.heartbeatConnectTimeout=1500 13 | mongo.minHeartbeatFrequency=5 14 | mongo.heartbeatFrequency=10 15 | 16 | #此参数跟connectionsPerHost的乘机为一个线程变为可用的最大阻塞数,超过此乘机数之后的所有线程将及时获取一个异常.eg.connectionsPerHost=10 and threadsAllowedToBlockForConnectionMultiplier=5,最多50个线程等级一个链接,推荐配置为5 17 | mongo.threadsAllowedToBlockForConnectionMultiplier=10 18 | #链接超时的毫秒数,0表示不超时,此参数只用在新建一个新链接时,推荐配置10,000. 19 | mongo.connectTimeout=10000 20 | #一个线程等待链接可用的最大等待毫秒数,0表示不等待,负数表示等待时间不确定,推荐配置120000 21 | mongo.maxWaitTime=120000 22 | #该标志用于控制socket保持活动的功能,通过防火墙保持连接活着 23 | mongo.socketKeepAlive=false 24 | #此参数表示socket I/O读写超时时间,推荐为不超时,即 0 Socket.setSoTimeout(int) 25 | mongo.socketTimeout=0 26 | 27 | 28 | #对mongo实例来说,每个host允许链接的最大链接数,这些链接空闲时会放入池中,如果链接被耗尽,任何请求链接的操作会被阻塞等待链接可用 29 | mongo.connectionsPerHost=1500 30 | #当链接空闲时,空闲线程池中最大链接数 31 | minPoolsSize=5 32 | #true:假如链接不能建立时,驱动将重试相同的server,有最大的重试次数,默认为15次,这样可以避免一些server因为一些阻塞操作零时down而驱动抛出异常,这个对平滑过度到一个新的master,也是很有用的,注意:当集群为复制集时,驱动将在这段时间里,尝试链接到旧的master上,而不会马上链接到新master上 33 | #false 当在进行socket读写时,不会阻止异常抛出,驱动已经有自动重建破坏链接和重试读操作. 推荐配置false 34 | mongo.autoConnectRetry=false 35 | #重新打开链接到相同server的最大毫秒数,推荐配置为0,如果 autoConnectRetry=true,表示时间为15s 36 | #com.jd.mongodbclient2.mongo.JDClientMongo.maxAutoConnectRetryTime=false 37 | #表示当没有手动关闭游标时,是否有一个自动释放游标对象的方法,如果你总是很小心的关闭游标,则可以将其设为false 推荐配置true 38 | #com.jd.mongodbclient2.mongo.JDClientMongo.cursorFinalizerEnabled=true 39 | 40 | #安全模式 41 | com.jd.mongodbclient2.driver.MongoDBDriver.safe=true 42 | #为true表示读写分离 43 | mongo.slaveOk=false 44 | 45 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | org.springframework.data.mongodb 5 | mongodb 6 | war 7 | 1.0-SNAPSHOT 8 | progress Maven Webapp 9 | http://maven.apache.org 10 | 11 | 12 | 1.6.6 13 | 1.2.17 14 | UTF-8 15 | 16 | 17 | 18 | 19 | org.springframework.data 20 | spring-data-mongodb 21 | 1.10.7.RELEASE 22 | 23 | 24 | 25 | org.springframework 26 | spring-test 27 | 4.2.8.RELEASE 28 | 29 | 30 | 31 | junit 32 | junit 33 | 4.12 34 | test 35 | 36 | 37 | 38 | 39 | org.slf4j 40 | slf4j-log4j12 41 | 1.7.25 42 | 43 | 44 | 45 | 46 | mongodb 47 | 48 | 49 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/mongodb/entity/Order.java: -------------------------------------------------------------------------------- 1 | package org.springframework.data.mongodb.entity; 2 | 3 | import org.springframework.data.annotation.Id; 4 | import org.springframework.data.mongodb.core.index.Indexed; 5 | import org.springframework.data.mongodb.core.mapping.Document; 6 | import org.springframework.data.mongodb.core.mapping.Field; 7 | import org.springframework.transaction.annotation.Transactional; 8 | 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | /** 13 | * Created by XiuYin.Cui on 2018/3/1. 14 | */ 15 | @Document 16 | public class Order { 17 | 18 | /** 19 | * @ID 生成MongoDB文档的_id 内容,如果不指定,MongoDB 会主动生成一个 20 | */ 21 | @Id 22 | private String id; 23 | 24 | /** 25 | * @Field 映射成MongoDB文档的字段内容 26 | */ 27 | @Field("client") 28 | private String customer; 29 | 30 | /** 31 | * @Indexed 是否在该字段上加上索引 32 | */ 33 | @Indexed 34 | private String type; 35 | 36 | 37 | /** 38 | * 集合类型最好使用 ? 不确定类型(或者说任意类型) 39 | * 否则会info(Found cycle for field 'itemList' in type 'Order' for path '')表明你的代码中有潜在的循环使用 40 | * 41 | * 像这样有另一个对象的集合,另一个对象不用加任何的MongoDB 注释 42 | */ 43 | private List itemList = new ArrayList(); 44 | 45 | public String getId() { 46 | return id; 47 | } 48 | 49 | public void setId(String id) { 50 | this.id = id; 51 | } 52 | 53 | public String getCustomer() { 54 | return customer; 55 | } 56 | 57 | public void setCustomer(String customer) { 58 | this.customer = customer; 59 | } 60 | 61 | public String getType() { 62 | return type; 63 | } 64 | 65 | public void setType(String type) { 66 | this.type = type; 67 | } 68 | 69 | public List getItemList() { 70 | return itemList; 71 | } 72 | 73 | public void setItemList(List itemList) { 74 | this.itemList = itemList; 75 | } 76 | 77 | @Override 78 | public String toString() { 79 | return "Order{" + 80 | "id='" + id + '\'' + 81 | ", customer='" + customer + '\'' + 82 | ", type='" + type + '\'' + 83 | ", itemList=" + itemList + 84 | '}'; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/main/resources/log4j.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /src/main/java/org/springframework/data/mongodb/config/MongoConfig.java: -------------------------------------------------------------------------------- 1 | package org.springframework.data.mongodb.config; 2 | 3 | import com.mongodb.Mongo; 4 | import com.mongodb.MongoClientOptions; 5 | import com.mongodb.MongoCredential; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.ComponentScan; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.context.annotation.PropertySource; 10 | import org.springframework.core.env.Environment; 11 | import org.springframework.data.mongodb.core.MongoClientFactoryBean; 12 | import org.springframework.data.mongodb.core.MongoTemplate; 13 | import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; 14 | 15 | /** 16 | * Created by XiuYin.Cui on 2018/3/1. 17 | */ 18 | @Configuration 19 | @EnableMongoRepositories(basePackages = "org.springframework.data.mongodb",repositoryImplementationPostfix = "Impl") //启用MongoDB的Repository功能 20 | @ComponentScan(basePackages = "org.springframework.data.mongodb") 21 | @PropertySource("classpath:mongo.properties") 22 | public class MongoConfig { 23 | 24 | /* 25 | * MongoClientFactoryBean 工厂bean 会负责创建Mongo实例。 26 | * */ 27 | @Bean(name = "mongo") 28 | public MongoClientFactoryBean mongoClientFactoryBean(Environment env) { 29 | MongoClientOptions.Builder builder = MongoClientOptions.builder(); 30 | MongoClientOptions build = builder.build(); 31 | MongoCredential credential = MongoCredential.createCredential( 32 | env.getProperty("mongo.user", String.class), 33 | env.getProperty("mongo.database", String.class), 34 | env.getProperty("mongo.password", String.class).toCharArray()); 35 | MongoClientFactoryBean mongoClientFactoryBean = new MongoClientFactoryBean(); 36 | mongoClientFactoryBean.setHost(env.getProperty("mongo.host", String.class)); 37 | mongoClientFactoryBean.setPort(env.getProperty("mongo.port", Integer.class)); 38 | mongoClientFactoryBean.setCredentials(new MongoCredential[]{credential}); 39 | mongoClientFactoryBean.setMongoClientOptions(build); 40 | return mongoClientFactoryBean; 41 | } 42 | 43 | /* 2.0 之后不支持这种构造器了 */ 44 | @Bean(name = "mongoTemplate") 45 | public MongoTemplate mongoTemplate(Mongo mongo, Environment env) { 46 | return new MongoTemplate(mongo, env.getProperty("mongo.database", String.class)); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/data/mongodb/Test01.java: -------------------------------------------------------------------------------- 1 | package org.springframework.data.mongodb; 2 | 3 | import com.mongodb.Mongo; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.data.mongodb.config.MongoConfig; 8 | import org.springframework.data.mongodb.core.MongoOperations; 9 | import org.springframework.data.mongodb.core.query.Criteria; 10 | import org.springframework.data.mongodb.core.query.Query; 11 | import org.springframework.data.mongodb.entity.Item; 12 | import org.springframework.data.mongodb.entity.Order; 13 | import org.springframework.test.context.ContextConfiguration; 14 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 15 | 16 | import java.util.ArrayList; 17 | import java.util.List; 18 | 19 | /** 20 | * Created by XiuYin.Cui on 2018/3/4. 21 | */ 22 | @RunWith(SpringJUnit4ClassRunner.class) 23 | @ContextConfiguration("classpath:applicationContext.xml") 24 | public class Test01 { 25 | 26 | 27 | //MongoOperations是MongoTemplate所实现的接口,不使用具体实现是一个好的做法,尤其是在注入的时候 28 | @Autowired 29 | private MongoOperations mongoOperations; 30 | 31 | //1、计算有多少条文档 32 | @Test 33 | public void count() { 34 | long order = mongoOperations.getCollection("order").count(); 35 | System.out.println(order); 36 | } 37 | 38 | //2、保存 39 | @Test 40 | public void save() { 41 | Order order = new Order(); 42 | order.setCustomer("customer"); 43 | order.setType("豪华型213"); 44 | 45 | List itemList = new ArrayList(); 46 | Item item = new Item(); 47 | item.setPrice(5.5); 48 | item.setProduct("产品"); 49 | item.setQuantity(5); 50 | itemList.add(item); 51 | itemList.add(item); 52 | order.setItemList(itemList); 53 | mongoOperations.save(order, "order"); 54 | } 55 | 56 | //3、查找 57 | @Test 58 | public void findById() { 59 | Order byId = mongoOperations.findById("5abb2a6303238760a48e3fd2", Order.class); 60 | System.out.println(byId); 61 | } 62 | 63 | @Test 64 | public void findAll() { 65 | List all = mongoOperations.findAll(Order.class); 66 | if (all != null && all.size() > 0){ 67 | for (Order order : all){ 68 | System.out.println(order); 69 | } 70 | } 71 | } 72 | 73 | 74 | //4、删除 75 | public void remove() { 76 | Order order = new Order(); 77 | order.setId("1"); 78 | mongoOperations.remove(order); 79 | } 80 | 81 | 82 | } 83 | -------------------------------------------------------------------------------- /src/main/resources/applicationContext.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 20 | 21 | 22 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/data/mongodb/Test04.java: -------------------------------------------------------------------------------- 1 | package org.springframework.data.mongodb; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.data.domain.Sort; 7 | import org.springframework.data.mongodb.core.MongoOperations; 8 | import org.springframework.data.mongodb.core.aggregation.*; 9 | import org.springframework.data.mongodb.core.query.Criteria; 10 | import org.springframework.test.context.ContextConfiguration; 11 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 12 | 13 | import java.util.List; 14 | 15 | /** 16 | * Created by XiuYin.Cui on 2018/4/18. 17 | */ 18 | @RunWith(SpringJUnit4ClassRunner.class) 19 | @ContextConfiguration("classpath:applicationContext.xml") 20 | public class Test04 { 21 | 22 | @Autowired 23 | private MongoOperations mongoOperations; 24 | 25 | /** 26 | * db.driverLocation.aggregate( 27 | * {"$match":{"areaCode":"350203"}}, 28 | * {"$project":{"driverUuid":1,"uploadTime":1,"positionType":1}}, 29 | * {"$group":{"_id":{"driverUuid":"$driverUuid","positionType":"$positionType"},"uploadTime":{"$first":{"$year":"$uploadTime"}},"count":{"$sum":1}}}, 30 | * {"$sort":{"count":-1}}, 31 | * {"$limit":100}, 32 | * {"$skip":50} 33 | * ) 34 | */ 35 | @Test 36 | public void test04(){ 37 | //match 38 | Criteria criteria = Criteria.where("350203").is("350203"); 39 | AggregationOperation matchOperation = Aggregation.match(criteria); 40 | //project 41 | AggregationOperation projectionOperation = Aggregation.project("driverUuid", "uploadTime", "positionType"); 42 | //group 43 | AggregationOperation groupOperation = Aggregation.group("driverUuid", "positionType") 44 | .first(DateOperators.dateOf("uploadTime").year()).as("uploadTime") 45 | .count().as("count"); 46 | //sort 47 | Sort sort = new Sort(Sort.Direction.DESC, "count"); 48 | AggregationOperation sortOperation = Aggregation.sort(sort); 49 | //limit 50 | AggregationOperation limitOperation = Aggregation.limit(100L); 51 | //skip 52 | AggregationOperation skipOperation = Aggregation.skip(50L); 53 | 54 | Aggregation aggregation = Aggregation.newAggregation(matchOperation, projectionOperation, groupOperation, sortOperation, limitOperation, skipOperation); 55 | AggregationResults driverLocation = mongoOperations.aggregate(aggregation, "driverLocation", Object.class); 56 | List mappedResults = driverLocation.getMappedResults(); 57 | 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/data/mongodb/Test02.java: -------------------------------------------------------------------------------- 1 | package org.springframework.data.mongodb; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.core.convert.converter.Converter; 7 | import org.springframework.data.domain.Page; 8 | import org.springframework.data.domain.Pageable; 9 | import org.springframework.data.domain.Sort; 10 | import org.springframework.data.mongodb.core.MongoOperations; 11 | import org.springframework.data.mongodb.core.query.Criteria; 12 | import org.springframework.data.mongodb.core.query.Query; 13 | import org.springframework.data.mongodb.entity.Order; 14 | import org.springframework.test.context.ContextConfiguration; 15 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 16 | 17 | import java.util.ArrayList; 18 | import java.util.Iterator; 19 | import java.util.List; 20 | import java.util.regex.Pattern; 21 | 22 | /** 23 | * Created by XiuYin.Cui on 2018/3/27. 24 | */ 25 | @RunWith(SpringJUnit4ClassRunner.class) 26 | @ContextConfiguration("classpath:applicationContext.xml") 27 | public class Test02 { 28 | 29 | @Autowired 30 | private MongoOperations mongoOperations; 31 | 32 | /** 33 | * db.order.find({"client":"customer"}) 34 | */ 35 | @Test 36 | public void test01(){ 37 | Criteria criteria = Criteria.where("client").is("customer"); 38 | Query query = new Query(criteria); 39 | List orders = mongoOperations.find(query, Order.class); 40 | if (orders != null && orders.size() > 0){ 41 | for (Order order : orders){ 42 | System.out.println(order); 43 | } 44 | } 45 | } 46 | 47 | /** 48 | * db.order.find({"client":"customer","type":"豪华型"}) 49 | * and 50 | */ 51 | @Test 52 | public void test02(){ 53 | Criteria criteria = Criteria.where("client").is("customer"); 54 | criteria.and("type").is("豪华型"); 55 | Query query = new Query(criteria); 56 | List orders = mongoOperations.find(query, Order.class); 57 | if (orders != null && orders.size() > 0){ 58 | for (Order order : orders){ 59 | System.out.println(order); 60 | } 61 | } 62 | } 63 | 64 | /** 65 | * db.order.find({"type":/^豪华/}) 66 | * 正则表达式 67 | */ 68 | @Test 69 | public void test03(){ 70 | Criteria criteria = Criteria.where("client").is("customer"); 71 | criteria.and("type").regex("^豪华"); 72 | Query query = new Query(criteria); 73 | List orders = mongoOperations.find(query, Order.class); 74 | if (orders != null && orders.size() > 0){ 75 | for (Order order : orders){ 76 | System.out.println(order); 77 | } 78 | } 79 | } 80 | 81 | /** 82 | * db.order.find({"client":"customer"}).sort({"type":-1}) 83 | * 排序 84 | */ 85 | @Test 86 | public void test04(){ 87 | Criteria criteria = Criteria.where("client").is("customer"); 88 | Sort sort = new Sort(Sort.Direction.DESC,"type"); 89 | Query query = new Query(criteria).with(sort); 90 | List orders = mongoOperations.find(query, Order.class); 91 | if (orders != null && orders.size() > 0){ 92 | for (Order order : orders){ 93 | System.out.println(order); 94 | } 95 | } 96 | } 97 | 98 | /** 99 | * db.order.find({"client":"customer"}).skip(5).limit(5) 100 | * 分页 101 | */ 102 | @Test 103 | public void test05(){ 104 | Criteria criteria = Criteria.where("client").is("customer"); 105 | /*limit 是pageSize , skip 是 第几页*pageSize */ 106 | Query query = new Query(criteria).skip(5).limit(5); 107 | List orders = mongoOperations.find(query, Order.class); 108 | if (orders != null && orders.size() > 0){ 109 | for (Order order : orders){ 110 | System.out.println(order); 111 | } 112 | } 113 | } 114 | 115 | 116 | /** 117 | * 大于 小于 不等于 118 | */ 119 | @Test 120 | public void test06(){ 121 | Criteria criteria = Criteria.where("client").is("customer"); 122 | criteria.and("key").lt(""); //小于 123 | criteria.and("key").lte(""); //小于等于 124 | criteria.and("key").gt(""); //大于 125 | criteria.and("key").gte(""); //大于等于 126 | criteria.and("key").ne(""); //不等于 mongoDB 没有 eq(等于) 这个操作 127 | Query query = new Query(criteria); 128 | } 129 | 130 | /** 131 | * $in $size $elemMatch $exists 132 | */ 133 | @Test 134 | public void test07(){ 135 | List list = new ArrayList(); 136 | Criteria condition = Criteria.where("x").lt(10).and("x").gt(5); 137 | Criteria criteria = Criteria.where("client").is("customer"); 138 | criteria.and("key").in(list); 139 | criteria.and("key").size(3); //匹配key数组长度等于 3 的文档 140 | criteria.elemMatch(condition); //要求 x 的数组每个元素必须同时满足 大于5 小于10 141 | criteria.and("key").exists(true); 142 | Query query = new Query(criteria); 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /src/test/java/org/springframework/data/mongodb/Test03.java: -------------------------------------------------------------------------------- 1 | package org.springframework.data.mongodb; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.data.geo.*; 7 | import org.springframework.data.mongodb.core.MongoOperations; 8 | import org.springframework.data.mongodb.core.geo.GeoJson; 9 | import org.springframework.data.mongodb.core.geo.GeoJsonPolygon; 10 | import org.springframework.data.mongodb.core.query.Criteria; 11 | import org.springframework.data.mongodb.core.query.NearQuery; 12 | import org.springframework.data.mongodb.core.query.Query; 13 | import org.springframework.test.context.ContextConfiguration; 14 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 15 | 16 | import java.util.List; 17 | 18 | /** 19 | * Created by XiuYin.Cui on 2018/4/13. 20 | */ 21 | 22 | @RunWith(SpringJUnit4ClassRunner.class) 23 | @ContextConfiguration("classpath:applicationContext.xml") 24 | public class Test03 { 25 | 26 | private static final double EARTH_RADIUS = 6378137d; 27 | 28 | @Autowired 29 | private MongoOperations mongoOperations; 30 | 31 | /*near*/ 32 | 33 | /** 34 | * $near 查询附近位置 35 | * db.runCommand({ 36 | * geoNear: "driverPoint" , 37 | * near: {"lng":118.193828,"lat":24.492242} , 38 | * spherical: true, 39 | * maxDistance:10/3963.2, 40 | * distanceMultiplier:3963.2, 41 | * query:{"driverUuid":"d43bf3d759064ed69a914cb10a010e77"} 42 | * }) 43 | */ 44 | @Test 45 | public void nearTest() { 46 | Criteria criteria = Criteria.where("driverUuid").is("d43bf3d759064ed69a914cb10a010e77"); 47 | Query query = new Query(criteria); 48 | NearQuery nearQuery = NearQuery.near(118.194936, 24.491849) 49 | .distanceMultiplier(EARTH_RADIUS) 50 | .maxDistance(3000) 51 | .spherical(true) 52 | .query(query); 53 | GeoResults geoResults = mongoOperations.geoNear(nearQuery, Object.class); 54 | List> content = geoResults.getContent(); 55 | 56 | } 57 | 58 | /*nearSphere*/ 59 | @Test 60 | public void nearSphereTest(){ 61 | Point x = new Point(118.193828, 24.492242); 62 | Criteria criteria = Criteria.where("coordinate").nearSphere(x); 63 | criteria.maxDistance(3000 / EARTH_RADIUS); 64 | Query query = new Query(criteria); 65 | List objects = mongoOperations.find(query, Object.class); 66 | } 67 | 68 | 69 | /*within*/ 70 | 71 | /** 72 | * "$geoWithin"操作符找出完全包含在某个区域的文档? 73 | * db.driverPoint.find( 74 | * { 75 | * coordinate: { 76 | * $geoIntersects: { 77 | * $geometry: { 78 | * type: "Polygon" , 79 | * coordinates: [ 80 | * [ [ 118.193828, 24.492242 ], [ 118.193953, 24.702114 ], [ 118.19387, 24.592242 ],[ 118.193828, 24.492242 ]] 81 | * ] 82 | * } 83 | * } 84 | * } 85 | * } 86 | * ) 87 | */ 88 | @Test 89 | public void withInGeoJsonPolygonTest() { 90 | Point x = new Point(118.193828, 24.492242); 91 | Point y = new Point(118.193953, 24.702114); 92 | Point z = new Point(119.19387, 28.792242); 93 | Shape shape = new GeoJsonPolygon(x, y, z, x); 94 | Criteria criteria = Criteria.where("coordinate").within(shape); 95 | Query query = new Query(criteria); 96 | List objects = mongoOperations.find(query, Object.class); 97 | } 98 | 99 | 100 | /** 101 | * "$geoWithin"操作符找出矩形范围内的文档? 102 | * db.driverPoint.find( 103 | * { 104 | * coordinate: { 105 | * $geoWithin: { 106 | * $box: [ 107 | * [ 118.0,24.0 ], 108 | * [ 120.0,30.0 ] 109 | * ] 110 | * } 111 | * } 112 | * } 113 | * ) 114 | */ 115 | @Test 116 | public void withInBoxTest() { 117 | Point x = new Point(118.0, 24.0); 118 | Point y = new Point(120.0, 30.0); 119 | Shape shape = new Box(x, y); 120 | Criteria coordinate = Criteria.where("coordinate").within(shape); 121 | Query query = new Query(coordinate); 122 | List objects = mongoOperations.find(query, Object.class); 123 | } 124 | 125 | 126 | /** 127 | * $geoWithin"操作符找出圆形范围内的文档? 128 | * db.driverPoint.find( 129 | * { 130 | * coordinate: { 131 | * $geoWithin: { 132 | * $center: [ [ 118.067678, 24.444373] , 10 ] 133 | * } 134 | * } 135 | * } 136 | * ) 137 | */ 138 | @Test 139 | public void withInCircleTest() { 140 | Point point = new Point(118.067678, 24.444373); 141 | Distance distance = new Distance(10, Metrics.KILOMETERS); 142 | Shape shape = new Circle(point, distance); 143 | Criteria criteria = Criteria.where("coordinate").within(shape); 144 | Query query = new Query(criteria); 145 | List objects = mongoOperations.find(query, Object.class); 146 | } 147 | 148 | /** 149 | * "$geoWithin"操作符找出多边形范围内的文档? 150 | * db.driverPoint.find( 151 | * { 152 | * coordinate: { 153 | * $geoWithin: { 154 | * $polygon: [ [ 118.067678 , 24.444373 ], [ 119.067678 , 25.444373 ], [ 120.067678 , 26.444373 ] ] 155 | * } 156 | * } 157 | * } 158 | * ) 159 | */ 160 | @Test 161 | public void withInPolygonTest() { 162 | Point x = new Point(118.193828, 24.492242); 163 | Point y = new Point(118.193953, 24.702114); 164 | Point z = new Point(119.19387, 28.792242); 165 | Shape shape = new Polygon(x, y ,z); 166 | Criteria coordinate = Criteria.where("coordinate").within(shape); 167 | Query query = new Query(coordinate); 168 | mongoOperations.find(query, Object.class); 169 | } 170 | 171 | 172 | /** 173 | * $geoWithin"操作符找出球面圆形范围内的文档? 174 | * 175 | * db.driverPoint.find( 176 | * { 177 | * coordinate: { 178 | * $geoWithin: { 179 | * $centerSphere: [ [ 118.067678, 24.444373 ], 10/3963.2 ] 180 | * } 181 | * } 182 | * } 183 | * ) 184 | */ 185 | @Test 186 | public void withInCenterSphereTest(){ 187 | Circle circle = new Circle(118.067678 , 24.444373 , 10/3963.2); 188 | Criteria criteria = Criteria.where("coordinate").withinSphere(circle); 189 | Query query = new Query(criteria); 190 | List objects = mongoOperations.find(query, Object.class); 191 | } 192 | 193 | /*Intersects*/ 194 | 195 | /** 196 | * "$geoIntersects" 操作符找出与查询位置相交的文档 ? 197 | * db.driverPoint.find( 198 | * { 199 | * coordinate: { 200 | * $geoIntersects: { 201 | * $geometry: { 202 | * type: "Polygon" , 203 | * coordinates: [ 204 | * [ [ 118.193828, 24.492242 ], [ 118.193953, 24.702114 ], [ 118.19387, 24.592242 ],[ 118.193828, 24.492242 ]] 205 | * ] 206 | * } 207 | * } 208 | * } 209 | * } 210 | * ) 211 | */ 212 | @Test 213 | public void intersectsTest(){ 214 | Point x = new Point(118.193828, 24.492242); 215 | Point y = new Point(118.193953, 24.702114); 216 | Point z = new Point(119.19387, 28.792242); 217 | GeoJson geoJson = new GeoJsonPolygon(x, y, z, x); 218 | Criteria coordinate = Criteria.where("coordinate").intersects(geoJson); 219 | Query query = new Query(coordinate); 220 | List objects = mongoOperations.find(query, Object.class); 221 | } 222 | } 223 | --------------------------------------------------------------------------------