MongoDB:查询具有两个相等字段的文档,$ match和$ eq

Pet*_*son 14 database mongodb node.js npm aggregation-framework

如果我想要document.a == document.b,那么返回集合中所有文档的最佳方法是什么?

我试过了

db.collection.aggregate([ { $match: { $eq: [ '$a', '$b' ] } }])
Run Code Online (Sandbox Code Playgroud)

但它返回没有错误或结果,因为我认为它字面上匹配字符串"$ a"和"$ b".是否有不同的方法来指定这些是字段?

db.collection.aggregate([    { $project: { 
    eq: { $cond: [ { $eq: [ '$a', '$b' ] }, 1, 0 ] } 
} },
{ $match: { eq: 1 } }])
Run Code Online (Sandbox Code Playgroud)

上述工作,但需要额外的步骤,使用它找到的任何文件或预测所有可能的字段再次查询.

有没有更好的方法来实现此查询?

小智 10

如果我理解你的问题,你想要那些在field1和field2中具有相同值的文档.

为此尝试

db.coll.find({$where: function() { return this.field1 == this.field2 } } );
Run Code Online (Sandbox Code Playgroud)

或者更紧凑

db.coll.find({ $where : "this.field1 == this.field2" } );
Run Code Online (Sandbox Code Playgroud)

  • 我要指出的是`$where` 子句[不能使用索引](https://docs.mongodb.com/manual/reference/operator/query/where/#thinkations),并可能导致**性能不佳** . 要探索查询的性能,[阅读 cursor.explain()](https://medium.com/dbkoda/8a3d0c6c7e68) (3认同)

Syl*_*oux 6

基本上,您正在尝试执行自联接。MongoDB 不支持的操作。

关于$eq运营商,正如您所猜测的:

除了$project按照您的建议使用额外的步骤外,我不知道还有其他任何方法可以执行您需要的操作。

请注意,这是不显著更昂贵,反正你的查询不能使用任何索引和MongoDB会做一个全面的扫描。