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

相关推荐
Coder_Boy_4 分钟前
技术交流总结:分布式、数据库、Spring及SpringBoot核心知识点梳理(实现参考)
数据库·spring boot·分布式·spring·架构
想不明白的过度思考者6 分钟前
Spring Boot 实战:MyBatis 操作数据库(上)
java·数据库·spring boot·mysql·mybatis
此生只爱蛋8 分钟前
【MySQL】存储过程
数据库·mysql
白太岁11 分钟前
Redis:(6) 三级缓存+连接池与高性能 Redis 客户端封装
数据库·redis·缓存
山岚的运维笔记26 分钟前
SQL Server笔记 -- 第78章:MS SQL Server 基本 DDL 操作
数据库·笔记·sql·microsoft·oracle·sqlserver
Albert Edison6 小时前
【Python】学生管理系统
开发语言·数据库·python
heimeiyingwang10 小时前
企业供应链 AI 优化:需求预测与智能调度
大数据·数据库·人工智能·机器学习
山岚的运维笔记11 小时前
SQL Server笔记 -- 第73章:排序/对行进行排序
数据库·笔记·后端·sql·microsoft·sqlserver
XLYcmy11 小时前
智能体大赛 目录
数据库·ai·llm·prompt·agent·检索·万方
盟接之桥11 小时前
盟接之桥EDI软件:API数据采集模块深度解析,打造企业数据协同新引擎
java·运维·服务器·网络·数据库·人工智能·制造