本篇文章小编给大家分享一下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.
{
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}}})
结果为空集
茶杯头甜蜜终章dlc 官方手机版v1.0.0.3
下载火柴人传说暗影格斗内置菜单 最新版v3.0.1
下载荒野乱斗测试服 安卓版v61.10.3
下载荒野乱斗彩虹服 安卓版v61.10.3
下载寒霜启示录 安卓版v1.25.10
寒霜启示录是一款生存模拟游戏,不少玩家可能对于末日都有着自己
末日城堡免广告版 安卓最新版v0.7.1
末日城堡免广告版是一款非常好玩的模拟经营类游戏,内部可以不看
甜蜜人生模拟器 最新版v1.4.5
甜蜜人生模拟器是一款非常好玩的模拟恋爱手游,玩家在这里能够对
武器锻造师内置功能菜单 v10.4
武器锻造师内置菜单版是游戏的破解版本,在该版本中为玩家提供了
开放空间overfield 安卓版v1.0.5
开放空间Overfield是一款箱庭养成经营手游,让你在广阔