MongoDB:查询具有两个相等字段 $match 和 $eq 的文档 [英] MongoDB : querying documents with two equal fields, $match and $eq

查看:21
本文介绍了MongoDB:查询具有两个相等字段 $match 和 $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:

  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆