问题
如果MongoDB 数据库集合中仅存在一条记录
分析不信邪的我又尝试了喜闻乐见的小白查询
db.getCollection(‘Persion’).find({“name”: “赵小明”, “age”: 18})
这次结果为空,嗯,这才是我熟悉的Mongo嘛?
那这两次查询有啥区别呢?不同有两点
那我们将数据改为
解决此时,我们需要用到我们今天的主角 $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一下。
到此这篇关于MongoDB操作符之$elemMatch的文章就介绍到这了,更多相关MongoDB操作符之$elemMatch内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!