为数组元素指定多个条件 [英] Specify Multiple Criteria for Array Elements

查看:58
本文介绍了为数组元素指定多个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读mongodb的文档此处, 我无法理解这两个命令以及它们之间的区别.

I am reading the docs for mongodb here, I am not able to understand these two commands and the different between them.

db.users.find( { finished: { $elemMatch: { $gt: 15, $lt: 20 } } } )

我的理解:至少需要同时满足两个条件.

My Understanding : At least one element needs to satisfy both the conditions together.

元素组合满足条件 ......一个元素可以满足大于15的条件,另一个元素可以满足 小于20的条件,或者一个元素可以同时满足这两个条件

Combination of Elements Satisfies the Criteria ...one element can satisfy the greater than 15 condition and another element can satisfy the less than 20 condition, or a single element can satisfy both

db.users.find( { finished: { $gt: 15, $lt: 20 } } )

问题:数组上的范围匹配如何发生?

推荐答案

要了解文档的内容,您首先需要了解数组的范围查询的工作原理.

To understand what the documentation is saying you first need to understand how range query with array works.

假设您的收藏夹中包含以下文档:

Suppose you have the following document in your collection:

{ "finished" : [ 27, 3 ] },
{ "finished" : 17 }

第一个查询:

db.users.find( { "finished": { "$elemMatch": { "$gt": 15, "$lt": 20 } } } )

仅返回"finished"是数组的文档.这是因为 $elemMatch 运算符仅匹配字段为一个数组,其中一个元素满足所有查询条件.

Will only return the document where "finished" is an array. This is because $elemMatch operator only matches documents where the field is an array and where a single element satisfy all the query criteria.

但是第二个查询:

db.users.find( { "finished": { "$gt": 15, "$lt": 20 } } )

将返回两个文档,这可能不是您想要的,因为27大于20并且3小于15.这是因为27匹配第一个条件,而3匹配第二个条件.此行为是中提到的内容文档.

will return both documents which is probably not what you want as 27 is greater than 20 and 3 is less than 15. This is because 27 matches the first criteria and 3 the second. This behavior is what is mentioned in the documentation.

...一个元素可以满足大于15的条件,另一个元素可以满足小于20的条件,或者单个元素可以满足两个条件:

...one element can satisfy the greater than 15 condition and another element can satisfy the less than 20 condition, or a single element can satisfy both:

结论:

针对数组的范围查询将匹配数组中符合所有查询条件的一个或多个元素.

Conclusion:

Range queries against arrays will match as far as one or multiple elements in the array that match all the query criteria.

不要对数组使用范围查询.您会得到意想不到的结果.

Don't use range query with arrays. You will get unexpected result.

这篇关于为数组元素指定多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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