BasicDBObject查询MongoDB
1.查询举例
//查询条件设置 BasicDBObject queryCond = new BasicDBObject(); //单个字段 queryCond.put("data_source", "诊断记录"); //in 的用法 queryCond.put("patient_id", new BasicDBObject("$in", patientIdList)); //数组字段中匹配多个符合条件的值 queryCond.put("data", new BasicDBObject("$elemMatch", new BasicDBObject("key", "EGFR").append("value", "+"))); //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"); }
(17条消息) Java中mongodb使用MongoCollection和BasicDBObject条件查询_样young的博客-CSDN博客
2. Mongo聚合查询
(17条消息) mongodb联表查询_浅夏晴空的博客-CSDN博客_mongodb联表查询
(17条消息) MongoDB学习总结五(详细记录MongoDB Aggregation聚合框架常见操作)_丰丶的博客-CSDN博客
(17条消息) Mongo学习笔记(三) 通过Aggregation和lookup进行多级关联查询_nyzzht123的博客-CSDN博客_mongo 多层级查询
Aggregation aggregation = Aggregation.newAggregation( Aggregation.match(where("_id").is(subjectId)), Aggregation.project("title").andExpression("toString(_id)").as("id"), Aggregation.lookup(Fields.field("topic"),Fields.field("id"),Fields.field("subjectId"),Fields.field("topics")), Aggregation.unwind("topics"), Aggregation.project("title","id") .andExpression("toString(topics._id)").as("topics.id") .and("topics.name").as("topics.name") .and("topics.order").as("topics.order") .and("topics.type").as("topics.type"), Aggregation.lookup("topicOption","topics.id","topicId","topics.topicOptions"), Aggregation.group("id").first("title").as("title").push("topics").as("topics") );
1)第一个lookup后使用了unwind将单个Bson拆为Bson数组,这点不可缺少,不然第二层lookup可能会关联不上(跟MongoDB版本有关,低版本可能关联不了)
2)这里使用了比较蠢的方法project来将ObjectId转为String,后来发现其实有个更简单的pipeline addFields,这一点会在java代码中进行说明,这里作为学习历程就留着了
3)因为之前使用了unwind,最后使用了group再进行一次压缩聚合

浙公网安备 33010602011771号