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

MongoDB compare document fields in aggregation pipeline

我收集了如下文档:

{ 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 驱动程序来执行此操作。

谢谢!!

PS。它不相关,但实际上上面的文档是集合 "cities" 和 "persons" 中的 $lookup 阶段的输出,并在 $name/$mayor 上加入 .. 太酷了!! :D :D

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

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

  }
]);

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