如何在两个字段具有相同值的情况下返回文档 [英] How to return documents where two fields have same value

查看:66
本文介绍了如何在两个字段具有相同值的情况下返回文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在两个给定的字段中仅找到具有相同值的集合中的那些文档?

Is it possible to find only those documents in a collections with same value in two given fields?

{
    _id:    'fewSFDewvfG20df', 
    start:  10,
    end:    10
}

由于此处startend具有相同的值,因此将选择此文档.

As here start and end have the same value, this document would be selected.

我考虑过类似的事情...

I think about something like...

Collection.find({ start: { $eq: end } })

...无效,因为end必须是一个值.

... which wouldn't work, as end has to be a value.

推荐答案

您在这里有两个选择.第一种是使用 $where 运算符.

You have two options here. The first one is to use the $where operator.

Collection.find( { $where: "this.start === this.end" } )

第二个选项是使用聚合框架和 运算符.

The second option is to use the aggregation framework and the $redact operator.

Collection.aggregate([
    { "$redact": { 
        "$cond": [
            { "$eq": [ "$start", "$end" ] },
            "$$KEEP",
            "$$PRUNE"
        ]
    }}
])

哪个更好?

Which one is better?

$where运算符会执行JavaScript评估,并且无法利用索引,因此使用$where进行查询可能会导致应用程序性能下降.请参阅注意事项.如果使用$ where,则在$ where操作之前,每个文档都将从BSON转换为JavaScript对象,这将导致性能下降.当然,如果您有索引过滤器,则可以改进查询.另外,如果要根据用户输入动态构建查询,还会有安全隐患.

The $where operator does a JavaScript evaluation and can't take advantage of indexes so query using $where can cause a drop of performance in your application. See considerations. If you use $where each of your document will be converted from BSON to JavaScript object before the $where operation which, will cause a drop of performance. Of course your query can be improved if you have an index filter. Also There is security risk if you're building your query dynamically base on user input.

$where一样的$redact不使用索引,甚至不执行集合扫描,但是当您使用$redact时,由于它是标准的MongoDB运算符,因此查询性能会提高.话虽这么说,聚合选项要好得多,因为您始终可以使用$ match运算符过滤文档.

The $redact like the $where doesn't use indexes and even perform a collection scan, but your query performance improves when you $redact because it is a standard MongoDB operators. That being said the aggregation option is far better because you can always filter your document using the $match operator.

$where可以,但是可以避免.我也相信,只有在遇到架构设计问题时才需要$where.例如,在此处使用索引将另一个布尔字段添加到文档中可能是一个不错的选择.

$where here is fine but could be avoided. Also I believe that you only need $where when you have a schema design problem. For example adding another boolean field to the document with index can be a good option here.

这篇关于如何在两个字段具有相同值的情况下返回文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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