首页 > 解决方案 > 将具有多个 $expr 的 mongodb 查找写入 java

问题描述

我有以下查找脚本:-

{
  "$lookup": {
    "from": "table2",
    "let": {"s_id": "$s_id","s_date": "$s_date"},
    "pipeline": [{
      "$match": {
        "$expr": {"$eq": ["$$s_id","$s_id"]},
        "$expr": {"$eq": ["$$s_date","$s_date"]}
       }
      }
     ],
   "as": "table2_values"
  }
 }

$expr值将是动态的(在 1 个字段或超过 1 个字段上),但这里我以 2 个字段为例。我正在尝试将上面的聚合脚本写入 java。请你帮助我好吗

List<String> whereClauseTable1List = new ArrayList<>();
whereClauseTable1List.add("s_id");
whereClauseTable1List.add("s_date");

List<String> whereClauseTable2List = new ArrayList<>();
whereClauseTable2List.add("s_id");
whereClauseTable2List.add("s_date");

 BasicDBObject letTable1Var = new BasicDBObject();
 for(String whereClauseTable1: whereClauseTable1List){
        letTable1Var.put(whereClauseTable1,"$"+whereClauseTable1);
  }

   BasicDBObject pipeLineMatchExp = new BasicDBObject();
    int index = 0;
    for(String whereClauseTable2: whereClauseTable2List){
        pipeLineMatchExp.append("$expr", new BasicDBObject("$eq", new 
        Object[]{"$$" + whereClauseTable2, "$" + 
        whereClauseTable1List.get(index)}));
        index++;
    }

  DBObject lookupDBOp = new BasicDBObject(
            "$lookup",
            new BasicDBObject("from","table2")
                    .append("let", letTable1Var)
                    .append("pipeline",new Object[]{new 
                    BasicDBObject("$match", pipeLineMatchExp)})
                    .append("as", "table2_values")
    );

实际上BasicObject不带重复键,所以它总是有 1 个$expr条件。我想写上面的脚本

标签: javamongodbspring-bootaggregation-frameworkspring-data-mongodb

解决方案


推荐阅读