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

相关推荐
观远数据4 分钟前
消费品牌选型BI的能力边界:三类差异化场景的适配清单与排除项
数据库·人工智能·microsoft
TlSfoward14 分钟前
爬虫指纹漂移监控与回归测试:JA3/JA4 变化为什么会影响线上验证 TLSFOWARD
数据库·爬虫·网络协议·搜索引擎
cmes_love33 分钟前
期货Level2与股票逐笔行情数据有什么,如何下载
数据库·区块链
—Miss. Z—42 分钟前
计算机二级MySQL——基本操作题
数据库·mysql·oracle
eddietao1 小时前
MySQL+SQLServer数据库-笔记
数据库·笔记·mysql
xd1855785551 小时前
SQL语句生成-基于鸿蒙的AI SQL语句生成应用开发实践
人工智能·sql·华为·harmonyos·鸿蒙
XS0301061 小时前
Spring AI第一课
数据库·人工智能·spring
LaughingZhu2 小时前
Product Hunt 每日热榜 | 2026-07-17
前端·数据库·人工智能·经验分享·mysql·chatgpt·html
DFT计算杂谈2 小时前
DeepSeek 集群服务器无root本地部署指南
数据库·人工智能·python·opencv·算法
潇凝子潇2 小时前
UnsupportedOperationException
java·前端·数据库