【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字段。

相关推荐
DBA_G42 分钟前
南大通用GBase 8s数据库新存储引擎核心能力二
数据库·微服务·架构
衣乌安、2 小时前
数据库事务原理与回滚机制
数据库
CodexDave3 小时前
PostgreSQL 明明有索引却选了 Nested Loop:从行数误判修正执行计划
数据库·postgresql·执行计划·扩展统计·nestedloop
czhaii5 小时前
STC ai助手单片机工程项目创建实例
数据库·mongodb
山峰哥5 小时前
数据库性能救星:Explain执行计划深度拆解
服务器·开发语言·数据库·sql·启发式算法
oradh6 小时前
Oracle 11g rac IP地址修改(public ip、vip、scan ip、priviate ip)
数据库·tcp/ip·oracle·rac ip地址修改
YOU OU6 小时前
Redis哨兵 & 集群
数据库·redis·sentinel
小罗水6 小时前
第8章 文档解析与文本切片
数据库·spring·spring cloud·微服务
瞬间&永恒~6 小时前
【MySQL】 主从复制多拓扑搭建实验
运维·数据库·mysql·云原生