package com.man.tools.mongodb.factory;import cn.hutool.core.annotation.AnnotationUtil;import cn.hutool.json.JSONObject;import cn.hutool.json.JSONUtil;import com.theone.date.util.DateUtil;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.data.domain.Sort;import org.springframework.data.mongodb.core.MongoTemplate;import org.springframework.data.mongodb.core.index.CompoundIndex;import org.springframework.data.mongodb.core.index.CompoundIndexes;import org.springframework.data.mongodb.core.index.Index;import org.springframework.data.mongodb.core.index.IndexInfo;import java.util.Date;import java.util.HashSet;import java.util.Map;import java.util.Set;public class MongoJpaCollectionFactory { protected static final Logger LOGGER = LoggerFactory.getLogger(MongoJpaCollectionFactory.class); public static String getCollectionName(String docName, Date date) { return docName + DateUtil.format(date, DateUtil.yyyyMM); } public static void creatIndex(MongoTemplate mongoTemplate, String collectionName, Class<?> aClass) { Set
package com.man.tools.mongodb;import org.springframework.data.annotation.Id;import org.springframework.data.mongodb.core.index.CompoundIndex;import org.springframework.data.mongodb.core.index.CompoundIndexes;import org.springframework.data.mongodb.core.mapping.document;@document(collection = "TestDoc")@CompoundIndexes({ @CompoundIndex(name = "age_-1_name_1", def = "{age:-1,name:1}", background = true)})public class TestDoc{ @Id private String id; private Integer age; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; }}
测试@RunWith(SpringJUnit4ClassRunner.class)//启动Spring@SpringBootTest(classes = Application.class)public class baseTest {@Resource private MongoTemplate mongoTemplate;@Testpublic void testIndexOp() { // 按年分表ArrayList