Skip to Content
MongoDB权威指南(第3版)
book

MongoDB权威指南(第3版)

by Shannon Bradshaw, Eoin Brazil, Kristina Chodorow
November 2021
Intermediate to advanced
410 pages
12h 1m
Chinese
Posts & Telecom Press
Content preview from MongoDB权威指南(第3版)
查询
53
5.
数组与范围查询的相互作用
文档中的标量(非数组元素)必须与查询条件中的每一条子句相匹配。如果使用
{"x" :
{"$gt" : 10, "$lt" : 20}}
进行查询,那么
"x"
必须同时满足大于
10
且小于
20
。然而,
如果文档中的
"x"
字段是一个数组,那么当
"x"
键的某一个元素与查询条件的任意一条语
句相匹配(
查询条件中的每条语句可以匹配不同的数组元素
)时,此文档也会被返回。
理解这种行为最好的方式就是来看一个例子。假设现在有如下几个文档:
{"x" : 5}
{"x" : 15}
{"x" : 25}
{"x" : [5, 25]}
如果想找出
"x"
的值在
10
20
之间的所有文档,那么你可能会本能地构建这样的查
询,即
db.test.find({"x" : {"$gt" : 10, "$lt" : 20}})
,然后期望它会返回一个文档:
{"x" : 15}
。然而,当实际运行时,我们得到了两个文档,如下所示:
> db.test.find({"x" : {"$gt" : 10, "$lt" : 20}})
{"x" : 15}
{"x" : [5, 25]}
5
25
都不在
10
20
之间,但由于
25
与查询条件中的第一个子句(
"x"
的值大于
10
相匹配,
5
与查询条件中的第二个子句
"x"
的值小于
20
)相匹配,因此这个文档会被
返回。
这样就使得针对数组的范围查询基本上失去了作用:一个范围会匹配任何多元素数组。有
几种方法可以获得预期的行为。
可以使用
"$elemMatch"
强制
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

大数据项目管理:从规划到实现

大数据项目管理:从规划到实现

Ted Malaska, Jonathan Seidman
Go程序设计语言

Go程序设计语言

艾伦A. A.多诺万, 布莱恩W. 柯尼汉
Spark快速大数据分析(第2版)

Spark快速大数据分析(第2版)

Jules S. Damji, Brooke Wenig, Tathagata Das, Denny Lee
Kafka权威指南(第2版)

Kafka权威指南(第2版)

Gwen Shapira, Todd Palino, Rajini Sivaram, Krit Petty

Publisher Resources

ISBN: 9787115576538