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

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

问题描述

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

<代码>{_id: 'fewSFDewvfG20df',开始:10,结束: 10}

因为这里的startend具有相同的值,这个文档将被选中.

我在考虑类似……

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

...这是行不通的,因为 end 必须是一个值.

解决方案

这里有两个选项.第一个是使用 $where 运算符.

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

第二种选择是使用聚合框架和$redact 运算符.

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

<块引用>

哪个更好?

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

$redact$where 一样不使用索引,甚至不执行集合扫描,但是当您 $redact 因为它是标准的 MongoDB 操作符.话虽如此,聚合选项要好得多,因为您始终可以使用 $match 运算符过滤文档.

$where 这里很好,但可以避免.另外我相信当您遇到架构设计问题时,您只需要 $where .例如,在这里向带有索引的文档添加另一个布尔字段可能是一个不错的选择.

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

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

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

I think about something like...

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

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

解决方案

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?

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.

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 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天全站免登陆