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

相关推荐
薛定谔的算法6 小时前
phoneGPT:构建专业领域的检索增强型智能问答系统
前端·数据库·后端
Databend8 小时前
Databend 亮相 RustChinaConf 2025,分享基于 Rust 构建商业化数仓平台的探索
数据库
得物技术8 小时前
破解gh-ost变更导致MySQL表膨胀之谜|得物技术
数据库·后端·mysql
似水流年流不尽思念12 小时前
MongoDB 有哪些索引?适用场景?
后端·mongodb
Raymond运维13 小时前
MariaDB源码编译安装(二)
运维·数据库·mariadb
沢田纲吉13 小时前
🗄️ MySQL 表操作全面指南
数据库·后端·mysql
RestCloud1 天前
SQL Server到Hive:批处理ETL性能提升30%的实战经验
数据库·api
RestCloud1 天前
为什么说零代码 ETL 是未来趋势?
数据库·api
ClouGence1 天前
CloudCanal + Paimon + SelectDB 从 0 到 1 构建实时湖仓
数据库
DemonAvenger2 天前
NoSQL与MySQL混合架构设计:从入门到实战的最佳实践
数据库·mysql·性能优化