MongoDB:查询具有两个相等字段($ match和$ eq)的文档 [英] MongoDB : querying documents with two equal fields, $match and $eq
问题描述
如果我想要document.a == document.b,返回集合中所有文档的最佳方法是什么?
What is the best way to return all documents in a collection if I want document.a == document.b?
我尝试过
db.collection.aggregate([ { $match: { $eq: [ '$a', '$b' ] } }])
但是它返回没有错误或结果,因为我假设它实际上是匹配字符串"$ 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?
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?
推荐答案
基本上,您正在尝试执行自我连接. MongoDB不支持的操作.
Basically, you are trying to perform a self join. An operation not supported by MongoDB.
关于$eq
运算符,正如您所猜测的那样:
Concerning the $eq
operator, as you guessed:
- 根据设计,
$eq
比较查询运算符匹配针对 value 的字段. - 但是
$eq
比较聚合运算符比较该值两个表达式中的一个.
- By design, the
$eq
comparison query operator match a field against a value. - But the
$eq
comparison aggregation operator compare the value of two expressions.
除了您建议使用额外的$project
步骤之外,我不知道其他任何方法来执行所需的操作.
I don't know any other way to perform what you need than using an extra $project
step as you suggested.
请注意,这并不昂贵,因为无论如何,您的查询不能使用任何索引,MongoDB会进行全面扫描.
Please note this is not significantly more expensive as, anyway, your query cannot use any index and MongoDB will do a full scan.
这篇关于MongoDB:查询具有两个相等字段($ match和$ eq)的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!