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

相关推荐
Boop_wu14 分钟前
[Java EE 进阶]Mybatis进阶(动态SQL)
java·数据库·maven·mybatis
Elastic 中国社区官方博客17 分钟前
使用 EDOT Browser 和 Kibana 进行 OpenTelemetry 浏览器端埋点
大数据·服务器·数据库·elasticsearch·搜索引擎·单元测试·可用性测试
星轨zb31 分钟前
为什么Mysql需要索引以及如何应用到项目中
数据库·mysql
Old Uncle Tom1 小时前
提示词编写规范
数据库·算法
l1t1 小时前
DeepSeek总结的Postgres 扩展天花板:当一个实例试图包揽一切时
数据库·postgresql
我要升天!1 小时前
C语言连接 MySQL:libmysqlclient 获取方式详解
c语言·开发语言·数据库·mysql·adb
juniperhan2 小时前
Flink 系列第17篇:Flink Table&SQL 核心概念、原理与实战详解
大数据·数据仓库·分布式·sql·flink
Irene19912 小时前
SQL 中的大小写规则总结:关键字、函数名不区分大小写(建议大写),字符串值、日期格式符严格区分大小写
sql·大小写规范
roman_日积跬步-终至千里3 小时前
【系统架构师案例题-知识点】数据库与缓存设计
数据库·缓存·系统架构
不剪发的Tony老师3 小时前
DBcooper:一款面向开发者的现代数据库客户端
数据库·sql