mongotemplate Criteria 和 Query的api有时候不是很方便动态构建语句,比如Query.query().fields().include().include(),想根据条件判断传入include就不太好处理,或者有些更灵活的场景,可以用这种方式:
BasicDBObject queryDBObject = new BasicDBObject();
if (!CollectionUtils.isEmpty(names)) queryDBObject.append(datasourceConf.getNameField(), new BasicDBObject("$in", names));
BasicDBObject project = new BasicDBObject("_id", 1);
if (StringUtils.hasLength(datasourceConf.getNameField())) project.append(datasourceConf.getNameField(), 1);
if (StringUtils.hasLength(datasourceConf.getTitleField())) project.append(datasourceConf.getTitleField(), 1);
if (StringUtils.hasLength(datasourceConf.getDigestField())) project.append(datasourceConf.getDigestField(), 1);
if (StringUtils.hasLength(datasourceConf.getMainbodyField())) project.append(datasourceConf.getMainbodyField(), 1);
BasicDBObject projectDBObject = new BasicDBObject("$project", project);
List list = new ArrayList<>();
list.add(queryDBObject);
list.add(projectDBObject);
MongoCursor<Document> iterator = mongoTemplate.getCollection(datasourceConf.getTableName()).aggregate(list).iterator();
while (iterator.hasNext()) {}