mongodb自定义查询,表连接查询,Aggregation高级使用

一、背景

近期需要,查询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("$
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值