SpringBoot整合Jongo

1. 配置文件

pom

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>3.11.2</version>
    </dependency>
    <dependency>
        <groupId>org.jongo</groupId>
        <artifactId>jongo</artifactId>
        <version>1.3.0</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-joda</artifactId>
        <version>2.9.7</version>
    </dependency>
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>2.7</version>
    </dependency>
<dependencies>

yml

server:
  port: 80

jongo:
  host: localhost
  port: 27017
  database: curd

2.Jongo常用方法

save(Object o)新增
insert(Object o)新增
insert(Object... o)新增
remove()删除集合全部内容
remove(ObjectId)根据Id删除
remove(String query)根据条件删除
remove(String query ,Object o)根据条件删除
find()查询全部
find(String query)根据条件查询
find(String query ,Object o)根据条件查询
findOne()查询一条
findOne(String query)根据条件查询一条
findOne(String query ,Object o)根据条件查询一条
update(ObjectId id)根据Id修改
update(String query, Object... parameters)根据条件修改
aggregate(String pipelineOperator)聚合查询
aggregate(String pipelineOperator, Object... parameters)聚合查询

3.代码

annotation
用于反射获取集合名称

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface Document {

    @AliasFor("collection")
    String value() default "";

    @AliasFor("value")
    String collection() default "";

}

config

@Configuration
@ConfigurationProperties(prefix = "jongo")
@Data
public class JongoConfig {

    private String host;
    private Integer port;
    private String database;

}

dao

@Repository
public abstract class BaseDAO<T> {

    private Class<T> clazz;

    private MongoCollection mongoCollection;

    @Autowired
    private JongoConfig jongoConfig;

    public BaseDAO() {
        clazz = getSuperClassGenericType();
    }

    private Class getSuperClassGenericType() {
        Type type = this.getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) type;
            clazz = (Class<T>) parameterizedType.getActualTypeArguments()[0];
        }
        return clazz;
    }

    @Bean
    protected MongoCollection getCollection() {
        String collectionName = clazz.getSimpleName().toLowerCase();
        if (clazz.isAnnotationPresent(Document.class)) {
            Document annotation = clazz.getAnnotation(Document.class);
            collectionName = annotation.collection();
        }
        Jongo jongo = new Jongo(new MongoClient(jongoConfig.getHost(), jongoConfig.getPort()).getDB(jongoConfig.getDatabase()));
        mongoCollection = jongo.getCollection(collectionName);
        return mongoCollection;
    }

    public WriteResult save(Object o) {
        WriteResult save = mongoCollection.save(o);
        return save;
    }

    public WriteResult insert(Object o) {
        WriteResult insert = mongoCollection.insert(o);
        return insert;
    }

    public WriteResult insert(Object... o) {
        WriteResult insert = mongoCollection.insert(o);
        return insert;
    }

    public WriteResult delete() {
        WriteResult remove = mongoCollection.remove();
        return remove;
    }

    public WriteResult delete(String id) {
        WriteResult remove = mongoCollection.remove(new ObjectId(id));
        return remove;
    }

    public WriteResult delete(String query, Object... o) {
        WriteResult remove = mongoCollection.remove(query, o);
        return remove;
    }

    public List<T> find() {
        MongoCursor<T> as = mongoCollection.find().as(clazz);
        return toList(as);
    }

    public List<T> find(String query, Object... o) {
        MongoCursor<T> as = mongoCollection.find(query, o).as(clazz);
        return toList(as);
    }

    public T findOne() {
        T as = mongoCollection.findOne().as(clazz);
        return as;
    }

    public T findOne(String query, Object... o) {
        T as = mongoCollection.findOne(query, o).as(clazz);
        return as;
    }

    public WriteResult update(String id, T t) {
        WriteResult update = mongoCollection.update(new ObjectId(id)).with(t);
        return update;
    }

    public WriteResult update(String query, T t, Object... o) {
        WriteResult update = mongoCollection.update(query, o).with(t);
        return update;
    }

    public WriteResult updateMulti(String query, T t, Object... o) {
        WriteResult update = mongoCollection.update(query, o).multi().with(t);
        return update;
    }

    public Aggregate aggregate(String pipelineOperator) {
        Aggregate aggregate = mongoCollection.aggregate(pipelineOperator);
        return aggregate;
    }

    protected List<T> toList(MongoCursor mongoCursor) {
        List<T> list = new ArrayList<>();
        while (mongoCursor.hasNext()) {
            Object next = mongoCursor.next();
            list.add((T) next);
        }
        return list;
    }

    protected <R> List<R> toList(Aggregate.ResultsIterator<R> resultsIterator) {
        List<R> list = new ArrayList<>();
        while (resultsIterator.hasNext()) {
            R next = (R) resultsIterator.next();
            list.add(next);
        }
        return list;
    }

}

@Repository
public class UserDAO extends BaseDAO<User> {
    
}

model

@Data
@Document(collection = "user")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @MongoObjectId
    private String _id;

    private String username;

    private String password;

    private String nickName;

    private Integer age;

    private List<String> address;

}

@Data
public class UserResVO implements Serializable {

    private static final long serialVersionUID = 1L;

    @MongoObjectId
    private String _id;

    private List<String> username;

    private List<String> nickName;

    private Integer count;

}

4.测试用例

@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class UserDAOTest {

    @Autowired
    UserDAO userDAO;

    @Test
    public void saveTest() {
        List<User> collect = IntStream.range(0, 100).mapToObj(num -> {
            User user = new User();
            user.setAge(18);
            user.setNickName("超级好看");
            user.setUsername("张三" + num);
            user.setPassword("123456");
            return user;
        }).collect(Collectors.toList());
        WriteResult save = userDAO.insert(collect);
        log.info("saveTest : {}", save);
    }

    @Test
    public void insertTest() {
        User user = new User();
        user.setAge(18);
        user.setNickName("超级好看");
        user.setUsername("张三");
        user.setPassword("123456");
        WriteResult insert = userDAO.insert(user);
        log.info("insertTest : {}", insert);
    }

    @Test
    public void insertTest2() {
        IntStream.range(0, 100).forEach(n -> {
            User user = new User();
            user.setAge(18);
            user.setNickName("超级好看");
            user.setUsername("张三" + n);
            user.setPassword("123456");
            userDAO.insert(user);
        });

    }

    @Test
    public void deleteTest() {
        WriteResult remove = userDAO.delete();
        log.info("deleteTest : {}", remove);
    }

    @Test
    public void deleteTest2() {
        String query = "{ " +
                "username : { $regex : #}" +
                "}";
        WriteResult remove = userDAO.delete(query, "^张三");
        log.info("deleteTest : {}", remove);
    }

    @Test
    public void findOneTest() {
        String query = "{ username : # }";
        User lis = userDAO.findOne(query, "lis");
        log.info("findOneTest : {}", lis);
    }

    @Test
    public void findTest() {
        String query = "{ " +
                "username : { $regex : #}" +
                "}";
        List<User> users = userDAO.find(query, "^张三");
        log.info("length : {} ,findTest : {}", users.size(), users);
    }

    @Test
    public void updateTest() {
        User one = userDAO.findOne();
        log.info("updateTest one :{}", one);
        User user = new User();
        user.setAge(19);
        WriteResult update = userDAO.update(one.get_id(), user);
        log.info("updateTest update:{}", update);
    }

    @Test
    public void updateTest2() {
        User user = new User();
        user.setAge(20);
        String query = "{ age : { $gte : # } }";
        WriteResult update = userDAO.update(query, user, 18);
        log.info("updateTest2 update:{}", update);
    }

    @Test
    public void updateMultiTest() {
        User user = new User();
        user.setAge(18);
        String query = "{ age : { $gte : # } }";
        WriteResult update = userDAO.updateMulti(query, user, 18);
        log.info("updateMultiTest update:{}", update);
    }

    @Test
    public void aggregateTest() {
        String match = "{ $match : { nickName: { $regex : '好看$' }, age : { $gte : 16, $lte : 18 } } }";
        String group = "{ $group : { _id: '$_id', username : { $push : '$username'}, nickName : { $push : '$nickName' }, count : { $sum : 1 } } }";
        Aggregate.ResultsIterator<UserResVO> as = userDAO.aggregate(match).and(group).as(UserResVO.class);
        List<UserResVO> users = userDAO.toList(as);
        log.info("length: {} ,aggregateTest:{}", users.size(), users);
    }
}

5.小练习

model

@Document(collection = "favorite_unit")
@Data
public class FavoriteUnit implements Serializable {

    private static final long serialVersionUID = 1L;

    private String _id;

    private String agentId; //代理人ID

    private String unitId; //单元ID

    private Date createTime;//创建时间

}

题目:获取上个月某个代理人添加的unitId列表和对应unitId的添加次数

答案

db.getCollection("favorite_unit").aggregate([
    { $match : {  
        createTime : { 
            $gt : ISODate("2020-06-01"),
            $lt : ISODate("2020-07-01")
            },
        agentId : "5c1cacc718aad600067b7aa0"
        },
    },
    { $group : { _id:"$unitId",count : {$sum: 1 }} }
])
private Date getDate(LocalDateTime localDateTime) {
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = localDateTime.atZone(zoneId);//Combines this date-time with a time-zone to create a  ZonedDateTime.
        return Date.from(zdt.toInstant());
}
String agentId = "5c1cacc718aad600067b7aa0";
LocalDateTime localDateTime = LocalDateTime.now().minusMonths(1);
LocalDateTime firstDayOfMonth = localDateTime.with(TemporalAdjusters.firstDayOfMonth());
firstDayOfMonth = LocalDateTime.of(firstDayOfMonth.toLocalDate(), LocalTime.MIN);
LocalDateTime lastDayOfMonth = localDateTime.with(TemporalAdjusters.lastDayOfMonth());
lastDayOfMonth = LocalDateTime.of(lastDayOfMonth.toLocalDate(), LocalTime.MAX);

String match = "{ $match : {  createTime : {  $gt : # , $lt :  # }, agentId :  # } }";
String group = "{ $group : { _id:'$unitId',count : {$sum: 1 } } }";
mongoCollection.aggregate(match, getDate(firstDayOfMonth), getDate(lastDayOfMonth), agentId).and(group).as(FavoriteUnit.class);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,616评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,020评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,078评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,040评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,154评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,265评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,298评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,072评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,491评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,795评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,970评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,654评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,272评论 3 318
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,985评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,223评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,815评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,852评论 2 351