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

相关推荐
weelinking3 小时前
【2026】08_Claude与版本控制:Git协作技巧
数据库·人工智能·git·python·数据挖掘·交互·cloudera
黄焖鸡能干四碗7 小时前
固定资产管理系统建设方案和源码(Java源码)
大数据·数据库·人工智能·物联网·区块链
JoneBB8 小时前
ABAP Webservice连接
运维·开发语言·数据库·学习
解决问题no解决代码问题8 小时前
从乱码到脱敏导出:TiDB CSV 导出实战全指南
数据库
未若君雅裁8 小时前
MySQL高可用与扩展-主从复制读写分离分库分表
java·数据库·mysql
2401_867623988 小时前
CSS Flex布局中如何设置子元素间距_掌握gap属性的现代用法
jvm·数据库·python
月落归舟8 小时前
一篇文章了解Redis内存淘汰机制与过期Key清理
数据库·redis·mybatis
phltxy9 小时前
Redis 事务
数据库·redis·缓存
康乾隆9 小时前
SQL Server Always On 重新添加从库步骤
数据库·sqlserver
环流_10 小时前
redis核心数据类型在java中的操作
java·数据库·redis