MongoDB比较聚合管道中的文档字段

时间:2015-11-20 18:33:02

标签: java mongodb aggregation-framework mongo-java-driver

我有一系列文件如下:

{ name : "John" , 
  age : 25.0 , 
  bornIn : "Milan" , 
  city : [ { 
        name : "Roma" , 
        state : "IT" , 
        mayor : "John"
        }]
 }
{ name : "Jim" , 
  age : 35.0 , 
  bornIn : "Madrid" , 
  city : [ { 
        name : "Madrid" , 
        state : "ESP" , 
        mayor : "Jim"
        }]
 }

我想检索所有字段$ bornIn等于字段$ city.name的文档。我需要将此作为管道的中间阶段,因此我无法使用$ where运算符。

我在网上搜索,我发现了一个建议来实现这样的事情:

 { $project:
       { matches:
            { $eq:[ '$bornIn', '$city.name' ] }
       } 
  }, 
  { $match:
        { matches:true }

  } ) 

但它既不通过shell也不通过Java驱动程序工作,因为它将字段标记为不同。 为了完整起见,我报告了我的代码:

final DBObject eq = new BasicDBObject();
LinkedList eqFields = new LinkedList();
eqFields.add("$bornIn");
eqFields.add("$city.name");
eq.put("$eq", eqFields);
projectFields.put("matches", eq);
final DBObject proj = new BasicDBObject("$project", projectFields);
LinkedList agg = new LinkedList();
agg.add(proj);
final AggregationOutput aggregate = table.aggregate( agg);

你有什么建议吗?我使用MongoDB 3.2,我需要通过Java Driver。

谢谢!

PS。这是不相关的,但实际上上面的文件是集合"城市"中的$ lookup阶段的输出。和#34;人物#34;,加入$ name / $ mayor ..这是非常酷! :D:D

1 个答案:

答案 0 :(得分:1)

关于Mongo如何处理深度相等搜索对象数组,我有点生疏,但这绝对可以用$unwind

来实现
db.foo.aggregate([
  {$unwind: "$city"},
  { $project:
       { matches:
            { $eq:[ '$bornIn', '$city.name' ] }
       } 
  }, 
  { $match:
        { matches:true }

  }
]);

我现在不在使用Mongo的计算机上,所以我的语法可能有些偏差。

相关问题