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

相关推荐
chushiyunen28 分钟前
r树索引、mysql对r树的支持
数据库·mysql
会编程的土豆28 分钟前
Redis Sorted Set(有序集合)详解
数据库·redis·bootstrap
Xiacqi140 分钟前
Java数据库连接--JDBC--DRUID
数据库·后端
Yushan Bai44 分钟前
ORACLE Enterprise Manager Cloud Control 系列测试3-Data Masking
数据库·oracle
罗超驿1 小时前
16.深入理解数据库事务:从转账场景剖析ACID四大特性与回滚(Rollback)机制
数据库·mysql
Yushan Bai2 小时前
ORACLE Enterprise Manager Cloud Control 系列测试2- 日常管理和SQL优化
数据库·oracle
-To be number.wan2 小时前
数据库单表查询全攻略
数据库·学习
文心快码BaiduComate2 小时前
520,Comate Mission模式跨越界限,和你达成最「深」联动
前端·数据库·后端
杨云龙UP2 小时前
Oracle RAC/ODA环境下如何准确查询PDB表空间已分配大小?一次说清Oracle表空间逻辑大小和ASM三副本实际占用_2026-05-19
linux·运维·数据库·sql·oracle·ffmpeg
@nengdoudou2 小时前
KingbaseES数据库MySQL模式使用 “GROUP BY“
数据库·mysql