Query、BasicDBObject、BasicDBList查询mongodb不同使用方式

一、使用Query 和 Criteria 进行查询

方式1

/**
     *根据patient_id获取MetadataHis中form_data.ZLFF=Immune的数据,返回结果按照exam_time升序排序
     */
    private List<CdrData> findMedicationByPatienId(String patientId) {
        //设置mongo查询条件
        Query query = new Query();
        Criteria c =new Criteria();
        c.and("patient_id").is(patientId);
        c.and("sub_source").is("用药史");
        c.and("data").elemMatch(Criteria.where("key").is("ZID").and("value").is(groupIdVal));
        query.addCriteria(c);
        query.addCriteria(Criteria.where("data.key").is("Immune"));
        query.with(new Sort(Sort.Direction.ASC, "survey_time"));
        return mongoTemplate.find(query, CdrData.class);
    }

方式2

Query query = new Query(Criteria.where("updateTime").lte(LocalDateTime.now()).gte(LocalDateTime.now().minusMonths(5)));
Book book = mongoTemplate.findOne(query, Book.class);

二、使用BasicDBObject 进行查询

查询条件设置

BasicDBObject queryCond = new BasicDBObject();
  • 单个字段
queryCond.put("data_source", "诊断记录"); 

相当于

db.collect.find({"data_source":"诊断记录"})
  • in 的用法
queryCond.put("patient_id", new BasicDBObject("$in", patientIdList));
  • 数组字段中匹配多个符合条件的值
queryCond.put("data", new BasicDBObject("$elemMatch", new BasicDBObject("key", "EGFR").append("value", "+")));
BasicDBObject query = new BasicDBObject();
BasicDBObject basicDbObject = new BasicDBObject();
LocalDateTime startTime = LocalDateTime.now();
basicDbObject.append("$gte", startTime.minusMonths(5));
basicDbObject.append("$lte", startTime.plusHours(2));
query.put("updateTime", basicDbObject);
MongoCursor<Document> book = mongoTemplate.getCollection("book").find(query).iterator();
while (book.hasNext()) {
	Document doc = book.next();
	Object pidObj = doc.get("_id");
	System.out.println(pidObj);
        }
  • exists 用法 1 代表存在该字段,字段值为 null的也算
queryCond.put("time_point_id", new BasicDBObject("$exists", 1));
  • 指定返回字段 0代表不返回,1代表返回,_id会默认返回(不返回需手动设置为0)
 BasicDBObject filterCond = new BasicDBObject();
 filterCond.put("_id", 0);
 filterCond.put("patient_id", 1);
 filterCond.put("data", 1);
  • 设置字段排序 1表示升序,-1表示倒序
BasicDBObject sortCond = new BasicDBObject();
sortCond.put("survey_time", 1);

查询结果

MongoCursor<Document> cursor = mongoTemplate.getCollection("collection_name").find(queryCond).projection(filterCond).sort(sortCond).iterator();

遍历结果

while (cursor.hasNext()) {
       Document doc = cursor.next();
       Object pidObj = doc.get("patient_id");
}

三、 BasicDBList

BasicDBList可以存放多个BasicDBObject条件

例如:我们查询onumber=002OR cname=zcy1

BasicDBList basicDBList=new BasicDBList();
basicDBList.add(new BasicDBObject("onumber","002"));
basicDBList.add(new BasicDBObject("cname","zcy1"));
DBObjectobj =new BasicDBObject();
obj.put("$or", basicDBList);
Query query=new BasicQuery(obj);

相当于

db.orders.find({$or:[{"onumber":"002"},{"cname":"zcy1"}]})

basicDBList.add方法是添加一个文档的查询条件

四、聚合查询,查出某一个字段出现次数前8的

  BasicDBObject queryCond = new BasicDBObject();
 
  queryCond.put("patient_id", new BasicDBObject("$in", patientTransferDepRepository.getPatientIdsByDep(depId)));
 Date startDate = null;
        Date endDate = null;
        if (month == null) {
            //统计当前年份 全部数据
            startDate = DateUtils.getYearFirst(year);
            endDate = DateUtils.getYearLast(year);
        } else {
            //统计当前 年-月 数据
            //手术时间在当年当月第一天和最后一天时间范围内(工具类month从0开始,此处month是从1开始,所以month-1)
            startDate = DateUtils.getFirstDayOfMonth(year, month-1);
            endDate = DateUtils.getLastDayOfMonth(year, month-1);
        }
        queryCond.put("survey_time", new BasicDBObject("$gte", DateUtils.parseDate(DateUtils.formatDate(startDate)+ " 00:00:00")).append("$lte", DateUtils.parseDate(DateUtils.formatDate(endDate)+ " 23:59:59")));
        aggregateCondList.add(new BasicDBObject("$match", queryCond));
 
        //unwind
        aggregateCondList.add(new BasicDBObject("$unwind", "$data"));
        // ZDLB 改为 手术名称的code(SSMC)
        aggregateCondList.add(new BasicDBObject("$match", new BasicDBObject("data.key", "SSMC")));
 
        //聚合条件 取出该年该月 手术名称:相应次数
        aggregateCondList.add(new BasicDBObject("$group", new BasicDBObject("_id", "$data.value").append("count" , new BasicDBObject("$sum", 1))));
 
        //排序,取手术名称对应次数前8的
        aggregateCondList.add(new BasicDBObject("$sort", new BasicDBObject("count", -1)));
        aggregateCondList.add(new BasicDBObject("$limit", 8));
 
        Map<String, Integer> resultMap = new LinkedHashMap<>(8);
        //遍历结果集
        MongoCursor<Document> cursor = mdcMongoTemplate.getCollection(CDR_DATA).aggregate(aggregateCondList).iterator();

你可能感兴趣的:(MongoDB,mongodb,python,windows)