MongoDB 数组类型查询 —— $elemMatch 操作符

本文详细介绍了MongoDB中$elemMatch数组查询操作符的使用方法,包括其语法、限制及实例应用,帮助读者理解如何精准查询数组元素。

描述

$elemMatch 数组查询操作用于查询数组值中至少有一个能完全匹配所有的查询条件的文档。语法格式如下:

{ <field>: { $elemMatch: { <query1>, <query2>, ... } } }

如果只有一个查询条件就没必要使用 $elemMatch。

限制

  1. 不能指定 $where 查询条件在 $elemMatch 内;
  2. 不能指定 $text 查询条件在 $elemMatch 内;

实例

有如下测试数据:

{ _id: 1, results: [ 82, 85, 88 ] }
{ _id: 2, results: [ 75, 88, 89 ] }

如下语句用于匹配 results 数组中含有值同时满足大于等于 80 且小于 85 的文档。

db.scores.find(
   { results: { $elemMatch: { $gte: 80, $lt: 85 } } }
)

如下查询结果,文档中 results 中 82 满足大于等于 80 且小于85。

{ "_id" : 1, "results" : [ 82, 85, 88 ] }

数组嵌套文档

例如有如下测试数据:

{ _id: 1, results: [ { product: "abc", score: 10 }, { product: "xyz", score: 5 } ] }
{ _id: 2, results: [ { product: "abc", score: 8 }, { product: "xyz", score: 7 } ] }
{ _id: 3, results: [ { product: "abc", score: 7 }, { product: "xyz", score: 8 } ] }

如下语句用于匹配 results 数组中含有值同时满足product 为 “xyz” 且 score 大于等于8 的文档。

db.survey.find(
   { results: { $elemMatch: { product: "xyz", score: { $gte: 8 } } } }
)

查询结果如下:

{ _id: 3, results: [ { product: "abc", score: 7 }, { product: "xyz", score: 8 } ] }

单查询条件

如果只有单个查询条件时没有必要使用 $elemMatch 操作符。例如如下查询:

// 没有必要使用 $elemMatch 操作符
db.survey.find(
   { results: { $elemMatch: { product: "xyz" } } }
)

$elemMatch 操作符只有单个查询条件,完全可以使用如下写法代替:

db.survey.find(
   { "results.product": "xyz" }
)

官网文档: https://docs.mongodb.com/manual/reference/operator/query/elemMatch/index.html

作者:学习园

来自个人博客: https://xuexiyuan.cn/article/detail/227.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

什码情况

你的鼓励就是我最大的动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值