来源:https://blog.csdn.net/qq_36331657/article/details/116431191
package com.mongo.springbootmongo;
import com.mongo.springbootmongo.model.Status;
import com.mongo.springbootmongo.model.User;
import com.mongodb.client.ListIndexesIterable;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.IndexOptions;
import com.mongodb.client.model.Indexes;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.bson.Document;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.*;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@Slf4j
public class SpringbootMongoApplicationTests {
private final String COLLECTION_NAME = "user";
@Autowired
private MongoTemplate mongoTemplate;
@Test
public void createCollection(){
mongoTemplate.createCollection(COLLECTION_NAME);
}
@Test
public void getCollectionNames() {
Set<String> collectionNames = mongoTemplate.getCollectionNames();
Assert.assertTrue(collectionNames.size() > 0 );
}
@Test
public void existsCollection() {
boolean user = mongoTemplate.collectionExists(COLLECTION_NAME);
Assert.assertTrue(user);
}
@Test
public void dropCollection() {
mongoTemplate.dropCollection(COLLECTION_NAME);
}
@Test
public void insert() {
User user = new User()
.setId("10")
.setAge(22)
.setSex("男")
.setRemake("无")
.setSalary(1500)
.setName("zhangsan")
.setBirthday(new Date())
.setStatus(new Status().setHeight(180).setWeight(150));
mongoTemplate.insert(user, COLLECTION_NAME);
}
@Test
public void insertMany(){
User user1 = new User()
.setId("10")
.setAge(22)
.setSex("男")
.setRemake("无")
.setSalary(1500)
.setName("shiyi")
.setBirthday(new Date())
.setStatus(new Status().setHeight(180).setWeight(150));
User user2 = new User()
.setId("12")
.setAge(22)
.setSex("男")
.setRemake("无")
.setSalary(1500)
.setName("shier")
.setBirthday(new Date())
.setStatus(new Status().setHeight(180).setWeight(150));
List<User> userList = new ArrayList<>();
userList.add(user1);
userList.add(user2);
Collection<User> newUserList = mongoTemplate.insert(userList, COLLECTION_NAME);
}
@Test
public void save() {
User user = new User()
.setId("13")
.setAge(22)
.setSex("男")
.setRemake("无")
.setSalary(2800)
.setName("kuiba")
.setBirthday(new Date())
.setStatus(new Status().setHeight(169).setWeight(150));
mongoTemplate.save(user, COLLECTION_NAME);
}
@Test
public void findAll() {
List<Status> statusList = mongoTemplate.findAll(Status.class);
List<User> documentList = mongoTemplate.findAll(User.class, COLLECTION_NAME);
for (User user : documentList) {
log.info("用户信息:{}", user);
}
}
@Test
public void findById() {
String id = "10";
User user = mongoTemplate.findById(id, User.class, COLLECTION_NAME);
log.info("用户信息:{}", user);
}
@Test
public void findOne() {
int age = 22;
Criteria criteria = Criteria.where("age").is(age);
Query query = new Query(criteria);
User user = mongoTemplate.findOne(query, User.class, COLLECTION_NAME);
log.info("用户信息:{}", user);
}
@Test
public void findByCondition() {
String sort = "age";
Criteria criteria = Criteria.where("sex").is("女");
Query query = new Query(criteria).with(Sort.by(sort));
User user = mongoTemplate.findOne(query, User.class, COLLECTION_NAME);
log.info("用户信息:{}", user);
}
@Test
public void findByConditionAndSortLimit() {
String sex = "男";
String sort = "age";
int limit = 2;
Criteria criteria = Criteria.where("sex").is(sex);
Query query = new Query(criteria).with(Sort.by(sort)).limit(limit);
List<User> documentList = mongoTemplate.find(query, User.class, COLLECTION_NAME);
for (User user : documentList) {
log.info("用户信息:{}", user);
}
}
@Test
public void findByConditionAndSortSkip() {
String sex = "男";
String sort = "age";
int skip = 1;
Criteria criteria = Criteria.where("sex").is(sex);
Query query = new Query(criteria).with(Sort.by(sort)).skip(skip);
List<User> documentList = mongoTemplate.find(query, User.class, COLLECTION_NAME);
for (User user : documentList) {
log.info("用户信息:{}", user);
}
}
@Test
public void findByExistsField() {
String field = "sex";
Criteria criteria = Criteria.where(field).exists(true);
Query query = new Query(criteria);
List<User> documentList = mongoTemplate.find(query, User.class, COLLECTION_NAME);
for (User user : documentList) {
log.info("用户信息:{}", user);
}
}
@Test
public void findByAndCondition() {
String sex = "男";
Integer age = 22;
Criteria criteriaSex = Criteria.where("sex").is(sex);
Criteria criteriaAge = Criteria.where("age").is(age);
Criteria criteria = new Criteria().andOperator(criteriaSex, criteriaAge);
Query query = new Query(criteria);
List<User> documentList = mongoTemplate.find(query, User.class, COLLECTION_NAME);
}
@Test
public void update() {
Criteria criteria = Criteria.where("age").is(30);
Query query = new Query(criteria);
Update update = new Update().set("age", 33).set("name", "zhangsansan");
UpdateResult result = mongoTemplate.upsert(query, update, User.class, COLLECTION_NAME);
String resultInfo = "匹配到" + result.getMatchedCount() + "条数据,对第一条数据进行了更改";
log.info("更新结果:{}", resultInfo);
}
@Test
public void updateFirst() {
Criteria criteria = Criteria.where("name").is("zhangsan");
Query query = new Query(criteria).with(Sort.by("age").ascending());
Update update = new Update().set("age", 30).set("name", "zhangsansan");
UpdateResult result = mongoTemplate.updateFirst(query, update, User.class, COLLECTION_NAME);
String resultInfo = "共匹配到" + result.getMatchedCount() + "条数据,修改了" + result.getModifiedCount() + "条数据";
log.info("更新结果:{}", resultInfo);
}
@Test
public void updateMany() {
Criteria criteria = Criteria.where("age").gt(28);
Query query = new Query(criteria);
Update update = new Update().set("age", 29).set("salary", "1999");
UpdateResult result = mongoTemplate.updateMulti(query, update, User.class, COLLECTION_NAME);
String resultInfo = "总共匹配到" + result.getMatchedCount() + "条数据,修改了" + result.getModifiedCount() + "条数据";
log.info("更新结果:{}", resultInfo);
}
@Test
public void remove() {
int age = 30;
String sex = "男";
Criteria criteria = Criteria.where("age").is(age).and("sex").is(sex);
Query query = new Query(criteria);
DeleteResult result = mongoTemplate.remove(query, COLLECTION_NAME);
String resultInfo = "成功删除 " + result.getDeletedCount() + " 条文档信息";
log.info(resultInfo);
}
@Test
public void findAndRemove() {
String name = "zhangsansan";
Criteria criteria = Criteria.where("name").is(name);
Query query = new Query(criteria);
User result = mongoTemplate.findAndRemove(query, User.class, COLLECTION_NAME);
String resultInfo = "成功删除文档信息,文档内容为:" + result;
log.info(resultInfo);
}
@Test
public void findAllAndRemove() {
int age = 22;
Criteria criteria = Criteria.where("age").is(age);
Query query = new Query(criteria);
List<User> resultList = mongoTemplate.findAllAndRemove(query, User.class, COLLECTION_NAME);
String resultInfo = "成功删除文档信息,文档内容为:" + resultList;
log.info(resultInfo);
}
@Test
public void aggregationGroupCount() {
AggregationOperation group = Aggregation.group("age").count().as("numCount");
Aggregation aggregation = Aggregation.newAggregation(group);
AggregationResults<Map> results = mongoTemplate.aggregate(aggregation, COLLECTION_NAME, Map.class);
for (Map result : results.getMappedResults()) {
log.info("{}", result);
}
}
@Test
public void aggregateGroupSort() {
AggregationOperation group = Aggregation.group("age")
.max("salary").as("ageSalary")
.count().as("ageCount");
AggregationOperation sort = Aggregation.sort(Sort.by("ageSalary").ascending());
Aggregation aggregation = Aggregation.newAggregation(group, sort);
AggregationResults<Map> results = mongoTemplate.aggregate(aggregation, COLLECTION_NAME, Map.class);
for (Map result : results.getMappedResults()) {
log.info("{}", result);
}
}
@Test
public void aggregateGroupLimit() {
AggregationOperation group = Aggregation.group("age")
.sum("salary").as("sumSalary")
.max("salary").as("maxSalary")
.min("salary").as("minSalary")
.avg("salary").as("avgSalary");
AggregationOperation limit = Aggregation.limit(5L);
Aggregation aggregation = Aggregation.newAggregation(group, limit);
AggregationResults<Map> results = mongoTemplate.aggregate(aggregation, COLLECTION_NAME, Map.class);
for (Map result : results.getMappedResults()) {
log.info("{}", result);
}
}
@Test
public void aggregateGroupSkip() {
AggregationOperation group = Aggregation.group("age")
.sum("salary").as("sumSalary")
.max("salary").as("maxSalary")
.min("salary").as("minSalary")
.avg("salary").as("avgSalary");
AggregationOperation limit = Aggregation.skip(2L);
Aggregation aggregation = Aggregation.newAggregation(group, limit);
AggregationResults<Map> results = mongoTemplate.aggregate(aggregation, COLLECTION_NAME, Map.class);
for (Map result : results.getMappedResults()) {
log.info("{}", result);
}
}
@Test
public void aggregateGroupProject() {
AggregationOperation group = Aggregation.group("age")
.max("salary").as("maxSalary")
.min("salary").as("minSalary");
AggregationOperation project = Aggregation.project("maxSalary");
Aggregation aggregation = Aggregation.newAggregation(group, project);
AggregationResults<Map> results = mongoTemplate.aggregate(aggregation, COLLECTION_NAME, Map.class);
for (Map result : results.getMappedResults()) {
log.info("{}", result);
}
}
@Test
public void aggregateProjectUnwind() {
AggregationOperation project = Aggregation.project("name", "age", "title");
AggregationOperation unwind = Aggregation.unwind("title");
Aggregation aggregation = Aggregation.newAggregation(project, unwind);
AggregationResults<Map> results = mongoTemplate.aggregate(aggregation, COLLECTION_NAME, Map.class);
for (Map result : results.getMappedResults()) {
log.info("{}", result);
}
}
@Test
public void createAscendingIndex() {
String field = "name";
String index = mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.ascending(field));
}
@Test
public void createDescendingIndex() {
String field = "name";
String index = mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.descending(field));
}
@Test
public void createCompositeIndex() {
String field1 = "name";
String field2 = "age";
String index = mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.ascending(field1, field2));
}
@Test
public void createTextIndex() {
String field = "name";
String index = mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.text(field));
}
@Test
public void createHashIndex() {
String field = "name";
String index = mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.hashed(field));
}
@Test
public void createUniqueIndex() {
String indexName = "name";
IndexOptions options = new IndexOptions();
options.unique(true);
String index = mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.ascending(indexName), options);
}
@Test
public void createPartialIndex() {
String field = "name";
IndexOptions options = new IndexOptions();
options.partialFilterExpression(Filters.exists("name", true));
String index = mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.ascending(field), options);
}
@Test
public void getIndexAll() {
ListIndexesIterable<org.bson.Document> indexList = mongoTemplate.getCollection(COLLECTION_NAME).listIndexes();
List<Document> list = new ArrayList<>();
for (Document document : indexList) {
log.info("索引列表:{}",document);
list.add(document);
}
}
@Test
public void removeIndex() {
String indexName = "name_1";
mongoTemplate.getCollection(COLLECTION_NAME).dropIndex(indexName);
}
@Test
public void removeIndexAll() {
mongoTemplate.getCollection(COLLECTION_NAME).dropIndexes();
}
}
|