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

相关推荐
Databend3 小时前
Databend Cloud 支持使用 IAM Role 访问 S3,减少长期密钥暴露风险
大数据·数据库·云原生
陈希1233 小时前
S3-08_MySQL 索引与慢查询优化:B+ 树、最左前缀与 EXPLAIN 实战
数据库·mysql
Decay__3 小时前
PostgreSQL 故障处理案例集 —— 高频故障定位与处置(复制中断、锁阻塞、磁盘满、误删、连接风暴、膨胀)
运维·数据库·sql·postgresql
qq_410960353 小时前
PostgreSQL vs MySQL:在数据统计报表与B
数据库·mysql·postgresql
PaperData3 小时前
2000-2025年“促进科技和金融结合”试点政策DID
数据库
啵啵啵鱼3 小时前
Chrome 内存泄漏诊断指南:从现象到根因的完整排查路径
数据库
中科三方3 小时前
新一代通信网建设实施方案:域名安全被纳入通信安全保障重点方向
数据库·安全·php
程序员张34 小时前
MySQL-GB级库备份还原
数据库·mysql
weixin_307779134 小时前
Jupyter SQL 表血缘分析并导出 Excel
开发语言·python·sql·算法·excel
tianyuanwo4 小时前
PostgreSQL 系统操作手册
数据库·postgresql