mongodb条件查询的两种方式

方法一:

        long systemTime = System.currentTimeMillis() / 1000;
        int endTime = (int) systemTime;
        int startTime = (int) (systemTime - 600);
        log.info("startTime={} endTime={} ", startTime, endTime);

        Query query = new Query();
        query.addCriteria(Criteria.where("timestamp").gte(startTime).lte(endTime));
        List chargeInfos = mongoTemplate.find(query, ChargeInfo.class, ConstantConfig.MONGODB_COLLECTION_NAME);
        log.info("chargeInfos:{}", JsonUtil.bean2Json(chargeInfos));

方法二:

        // 1. 查询10分钟之内的数据, 汇总10分钟以内的数据
        Mongo mongo = new Mongo();
        DB db = mongo.getDB(ConstantConfig.MONGODB_NAME);
        DBCollection users = db.getCollection(ConstantConfig.MONGODB_COLLECTION_NAME);
        BasicDBList condList = new BasicDBList();
        BasicDBObject cond1 = new BasicDBObject();
        BasicDBObject cond2 = new BasicDBObject(); // 此处不可用同一个con会产生覆盖
        cond1.append("timestamp", new BasicDBObject("$gte", startTime));
        cond2.append("timestamp", new BasicDBObject("$lte", endTime));
        condList.add(cond1);
        condList.add(cond2);
        BasicDBObject searchCond = new BasicDBObject();
        searchCond.put("$and", condList);
        DBCursor dbCursor = users.find(searchCond);
        String infos = JSON.serialize(dbCursor);
        List chargeInfos = JsonUtil.json2List(infos, ChargeInfo.class);
        log.info("chargeInfo:{}", chargeInfos.isEmpty() ? "no data" : chargeInfos);

比较两个方法,从代码简洁上看方法一更好,从代码理解上看方法二更接近于底层更好理解。

其中方法二作条件查询,查询条件需要作多个cond否则查询条件会被覆盖!

 

你可能感兴趣的:(---15.1,mongoDB)