帮助中心/最新通知

质量为本、客户为根、勇于拼搏、务实创新

< 返回文章列表

【服务器相关】MongoDB 数据库基础 之操作符中的$elemMatch问题详解

发表时间:2025-06-16 03:46:00 小编:主机乐-Yutio

问题

如果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内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!


联系我们
返回顶部