问题
如果MongoDB 数据库集合中仅存在一条记录
{ "_id" : ObjectId("5e6b4ef546b5f44e5c5b276d"), "name" : "赵小明", "used_name" : [ "赵明", "赵小朋" ], "age" : 16, "gender" : 0, "relatives" : [ { "name" : "赵刚", "relationship" : 0 }, { "name" : "秀英", "relationship" : 1 } ] }
我们执行查询
db.getCollection('Persion').find({"relatives.name": "赵刚", "relatives.relationship": 1})
此时会得到结果吗?
最开始我想当然的以为是不会出现结果的,但结果往往与期望背道而驰。
什么,一瞬间我陷入了迷茫,Mongo的查询结果不是必须都满足所有条件的吗?
分析
不信邪的我又尝试了喜闻乐见的小白查询
db.getCollection('Persion').find({"name": "赵小明", "age": 18})
这次结果为空,嗯,这才是我熟悉的Mongo嘛?
那这两次查询有啥区别呢?不同有两点
- 是否为二级字段
- 是否为数组
那我们将数据改为
{ "_id" : ObjectId("5e6b4ef546b5f44e5c5b276d"), "name" : "赵小明", "used_name" : [ "赵明", "赵小朋" ], "age" : 16, "gender" : 0, "relative" : { "name" : "赵刚", "relationship" : 0 } }
继续执行查询
db.getCollection('Persion').find({"relatives.name": "赵刚", "relatives.relationship": 1})
此次结果为空集
接下来尝试查询
db.getCollection('Persion').find({"relatives.name": "赵刚", "relatives.relationship": 0})
此次可得到一条结果
通过上述两次查询基本可以排除二级字段的影响
那就是数组的原因了,那具体是为什么呢?
将数据还原为最初的格式,继续进行不同的查询
db.getCollection('Persion').find({"relatives.name": "赵刚", "relatives.relationship": 2})
此次结果为空集
那我们可以得到结论,对于数组字段,每个查询条件仅需有数组中的一项满足条件即可,而不是数组中必须存在一项满足所有查询条件。
那如果我想达到后面的效果要怎么做呢?
解决
此时,我们需要用到我们今天的主角 $elemMatch
,它的官方定义是这样的:
The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.
{ <field>: { $elemMatch: { <query1>, <query2>, ... } } }
If you specify only a single condition in the $elemMatch expression, you do not need to use $elemMatch.You cannot specify a $where expression in an $elemMatch.
You cannot specify a $text query expression in an $elemMatch.
那上边的查询我们可以改成
db.getCollection('Persion').find({"relatives":{"$elemMatch":{"name": "赵四", "relationship": 0}}})
此时可以得到结果,但
db.getCollection('Persion').find({"relatives":{"$elemMatch":{"name": "赵四", "relationship": 1}}})
结果为空集
结语
此操作符和索引也有一些不得不说的事,今天就不在这里细说了,之后我会专门总结一篇有关MongoDB索引相关的博客
等不及的看官可以自行百度Google一下。
总结
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
RTX 5090要首发 性能要翻倍!三星展示GDDR7显存
三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。
首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。
据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。
更新日志
- 陈慧琳.2002-闪亮每一天新歌+精选2CD【正东】【WAV+CUE】
- 袁培华.1992-有缘【歌林】【WAV+CUE】
- 王瑞霞.1996-是我太软心【名冠】【WAV+CUE】
- 《谭维维 30首经典流行歌曲精选辑 2CD》[WAV/分轨][1.1GB]
- 《赵传 出道三十年全新大碟 你过得还好吗》[WAV/分轨][460MB]
- 《发烧四大天王 磁性男声HiFi发烧碟 2CD》[WAV/分轨][1GB]
- 黑神话悟空上品鼠司空精魄获取方法一览|上品鼠司空精魄收集攻略
- 《真三国无双:起源》新情报将于9月26日公开,实机演示亮相!
- 黑神话悟空上品鼠禁卫精魄获取方法一览|上品鼠禁卫精魄收集攻略
- 优美的旋律至真的情怀《品茶轻音乐·极品典藏Vol.1CD1》[WAV+CUE]
- 曾嵘《峥嵘岁月DSD(试音碟)》WAV+CUE
- 小提琴天碟AlfredoCampoli坎波利-贝多芬D大调小提琴协奏曲与普罗米修斯作品选FLAC
- 博主称本周游戏业内动荡无比:高价PS5 Pro、Xbox裁员等
- 米哈游也搞AI?米哈游AI大模型Glossa完成备案
- G胖变G瘦后:玩家担心其健康状况:如果他出事 游戏业将发生巨变