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

MongoDB : querying documents with two equal fields, $match and $eq

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

我试过了

db.collection.aggregate([ { $match: { $eq: [ '$a', '$b' ] } }])

但它 return 没有错误或结果,因为我假设它是字面上匹配字符串“$a”和“$b”。是否有不同的方式来指定这些字段?

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

以上方法有效,但需要额外的步骤,即再次查询它找到的任何文档或投影所有可能的字段。

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

基本上,您正在尝试执行自联接。 MongoDB.

不支持的操作

关于 $eq 运算符,如您所料:

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

请注意,这并不 显着 更昂贵,因为无论如何,您的查询不能使用任何索引并且 MongoDB 将进行全面扫描。

如果我理解你的问题是对的,那么你需要那些在 field1 和 field2 中具有相同值的文档。

为此尝试

db.coll.find({$where: function() { return this.field1 == this.field2 } } );

或更紧凑

db.coll.find({ $where : "this.field1 == this.field2" } );