一、背景
近期需要,查询mongodb的时候,需要像mysql一样进行联表查询。主表dmd_model,从表dmd_model_sub,两个表之间通过三个字段关联。
二、实现方案
2.1 创建BaseAggregateExpression.java
public class BaseAggregateExpression implements AggregationExpression {
private DBObject operator;
public BaseAggregateExpression(DBObject operator) {
this.operator = operator;
}
@Override
public Document toDocument(AggregationOperationContext context) {
return context.getMappedObject(Document.parse(operator.toString()));
}
}
2.2 代码写法
LookupOperation lookupOperation = LookupOperation.newLookup().
from("dmd_model_sub").
localField("tablename").
foreignField("tablename").
as("dmd_model_sub");
AggregationOperation mainMatch = Aggregation.match(criteria);
UnwindOperation unwind = Aggregation.unwind("dmd_model_sub", true);
// 过滤子集
Map<String, Object> map = new LinkedHashMap<>();
map.put("if", new BasicDBObject("$and",
new Object[] {
new BasicDBObject("$eq", Arrays.<Object> asList("$dsid", "$dmd_model_sub.dsid")),
new BasicDBObject("$eq", Arrays.<Object> asList("$schema", "$dmd_model_sub.schema")),
new BasicDBObject("$eq", Arrays.<Object> asList("$