MongoDB操作符中的$elemMatch问题
问题
如果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.
{
: { $elemMatch: { , , ... } } }
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一下。
您可能感兴趣的文章
- 12-31hiredis从安装到项目实战操作
- 12-31phpmyadmin登录时怎么指定服务器ip和端口
- 12-31MySQL线上死锁分析实战
- 12-31MySQL 触发器的使用和理解
- 12-31MySQL 字段默认值该如何设置
- 12-31Redis主从同步配置的方法步骤(图文)
- 12-31MySQL 字符串拆分操作(含分隔符的字符串截取)
- 12-31redis 交集、并集、差集的具体使用
- 12-31MySQL精讲之二:DML数据操作语句
- 12-31PostgreSQL判断字符串是否包含目标字符串的多种方法


阅读排行
推荐教程
- 12-23PL/SQL登录Oracle数据库报错ORA-12154:TNS:无法解析指定的连接标识符
- 12-23使用imp和exp命令对Oracle数据库进行导入导出操作详解
- 12-11mysql代码执行结构实例分析【顺序、分支、循环结构】
- 12-08添加mysql的用户名和密码是什么语句?
- 12-05mysql的事务,隔离级别和锁用法实例分析
- 12-23详解Oracle游标的简易用法
- 12-20PhpMyAdmin出现错误数据无法导出怎么办?
- 12-19Redis中实现查找某个值的范围
- 12-15浅析mysql迁移到clickhouse的5种方法
- 12-15CentOS7 64位下MySQL5.7安装与配置教程




