What is the best way to return all documents in a collection if I want document.a == document.b?
如果我想要document.a == document.b,那么返回集合中所有文档的最佳方法是什么?
I've tried
我试过了
db.collection.aggregate([ { $match: { $eq: [ '$a', '$b' ] } }])
But it returns with no errors or results, because I assume it is literally matching strings "$a" and "$b". Is there a different way to specify that these are fields?
但它返回没有错误或结果,因为我认为它字面上匹配字符串“$ a”和“$ b”。是否有不同的方法来指定这些是字段?
db.collection.aggregate([ { $project: {
eq: { $cond: [ { $eq: [ '$a', '$b' ] }, 1, 0 ] }
} },
{ $match: { eq: 1 } }])
The above works, but requires the additional step of querying again with whatever documents it found or projecting all possible fields.
上述工作,但需要额外的步骤,使用它找到的任何文件或预测所有可能的字段再次查询。
Is there a better way for achieving this query?
有没有更好的方法来实现此查询?
2 个解决方案
#1
1
Basically, you are trying to perform a self join. An operation not supported by MongoDB.
基本上,您正在尝试执行自联接。 MongoDB不支持的操作。
Concerning the $eq
operator, as you guessed:
关于$ eq运算符,正如您猜测的那样:
- By design, the
$eq
comparison query operator match a field against a value. - 根据设计,$ eq比较查询运算符将字段与值进行匹配。
- But the
$eq
comparison aggregation operator compare the value of two expressions. - 但$ eq比较聚合运算符比较两个表达式的值。
I don't know any other way to perform what you need than using an extra $project
step as you suggested.
我不知道如你所建议的那样使用额外的$ project步骤来执行你需要的任何其他方法。
Please note this is not significantly more expensive as, anyway, your query cannot use any index and MongoDB will do a full scan.
请注意,这并不是特别昂贵,因为无论如何,您的查询不能使用任何索引,MongoDB将进行全面扫描。
#2
3
If I understood your question right you want those documents that have same values in field1 and field2.
如果我理解你的问题,你想要那些在field1和field2中具有相同值的文档。
For this try
为此尝试
db.coll.find({$where: function() { return this.field1 == this.field2 } } );
or more compact
或者更紧凑
db.coll.find({ $where : "this.field1 == this.field2" } );
#1
1
Basically, you are trying to perform a self join. An operation not supported by MongoDB.
基本上,您正在尝试执行自联接。 MongoDB不支持的操作。
Concerning the $eq
operator, as you guessed:
关于$ eq运算符,正如您猜测的那样:
- By design, the
$eq
comparison query operator match a field against a value. - 根据设计,$ eq比较查询运算符将字段与值进行匹配。
- But the
$eq
comparison aggregation operator compare the value of two expressions. - 但$ eq比较聚合运算符比较两个表达式的值。
I don't know any other way to perform what you need than using an extra $project
step as you suggested.
我不知道如你所建议的那样使用额外的$ project步骤来执行你需要的任何其他方法。
Please note this is not significantly more expensive as, anyway, your query cannot use any index and MongoDB will do a full scan.
请注意,这并不是特别昂贵,因为无论如何,您的查询不能使用任何索引,MongoDB将进行全面扫描。
#2
3
If I understood your question right you want those documents that have same values in field1 and field2.
如果我理解你的问题,你想要那些在field1和field2中具有相同值的文档。
For this try
为此尝试
db.coll.find({$where: function() { return this.field1 == this.field2 } } );
or more compact
或者更紧凑
db.coll.find({ $where : "this.field1 == this.field2" } );