【sql】MongoDB 查询 高级用法

【sql】MongoDB 查询 高级用法

一、基本查询指定字段

复制代码
db.getCollection('students').find({}, {name: 1, score: 1})

二、指定字段别名

复制代码
db.getCollection('students').find({}, {"name":1, "score":1, "grade":"$grade.grade"})

这里将grade.grade字段的别名设置为grade。

三、限制子文档中的字段

在MongoDB中,子文档会被完整返回,包含文档中的所有字段。如果只需要返回子文档中的某些字段,可以使用elemMatch和 projection。

$elemMatch用于限制返回的数组元素,例如:

复制代码
db.getCollection('students').find({}, {scores: {$elemMatch: {type: "final", score: {$gt: 80}}}})

这里只返回scores数组中type为final且score大于80的元素。

$projection则可以限制返回的子文档中的字段:

复制代码
db.getCollection('students').find({}, {"name":1, "scores": {$elemMatch: {type: "final", score: {$gt: 80}}}}, {"scores.type": 0})

这里排除了返回的scores数组元素中的type字段。

四、排除指定字段

在MongoDB查询中,可以使用0将要排除的字段置为0。例如:

复制代码
db.getCollection('students').find({}, {"score": 0})

这里排除了返回的文档中的score字段。

相关推荐
瀚高PG实验室27 分钟前
瀚高企业版V9.1.1在pg_restore还原备份文件时提示extract函数语法问题
数据库·瀚高数据库
TDengine (老段)37 分钟前
TDengine Tag 设计哲学与 Schema 变更机制
大数据·数据库·物联网·时序数据库·iot·tdengine·涛思数据
YOU OU2 小时前
Spring IoC&DI
java·数据库·spring
Muscleheng3 小时前
Navicat连接postgresql时出现‘datlastsysoid does not exist‘报错
数据库·postgresql
罗超驿3 小时前
18.事务的隔离性和隔离级别:MySQL面试高频考点全解析
数据库·mysql·面试
jran-3 小时前
Redis 命令
数据库·redis·缓存
小江的记录本4 小时前
【Java基础】Java 8-21新特性:JDK21 LTS:虚拟线程、模式匹配switch、结构化并发、序列集合(附《思维导图》+《面试高频考点清单》)
java·数据库·python·mysql·spring·面试·maven
June`4 小时前
多线程redis下如何解决aof重写和rdb持久化的数据一致性问题
数据库·redis·缓存
二宝哥5 小时前
离线安装maven
java·数据库·maven
SZLSDH5 小时前
场景适配论 | 数字孪生IOC建设中渲染技术与智能体能力的协同逻辑
前端·数据库·ai·数字孪生·数据可视化·智能体