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

相关推荐
云和恩墨2 小时前
数据库一体机简史:从ODA到zData X,命名之中的玄机
数据库·vr
数据库小学妹3 小时前
KES是什么?国产数据库技术架构、核心能力与选型实战解析
数据库·经验分享·架构·国产数据库·数据库选型·信创数据库
衍生星球3 小时前
SpringBoot3 + Vue3 + 微信小程序如何学习,以及学哪些技术,组件
sql·微信小程序·uni-app·vue·springboot
Database_Cool_4 小时前
向量检索加速首选:阿里云 Tair 内置向量能力毫秒级召回
数据库·阿里云
强健的石头4 小时前
django文件对象是什么?
数据库·django·sqlite
ClouGence5 小时前
保障公共安全,一线治安机构实时数据应用与实践
数据库·mysql·postgresql
烟漠河洛5 小时前
线上事故复盘:Redis幂等性设计边界没覆盖跨状态请求,订单状态机直接崩了
数据库·redis·缓存
Minxinbb6 小时前
TDSQL for MySQL 服务器重启操作
数据库·mysql·dba
SelectDB6 小时前
Doris 实战:用 Colocate Join 消除 Shuffle,AB 指标计算性能提升 145 倍 🚀
数据库·性能优化·ab测试
PawSQL6 小时前
PawSQL 技术月报 | 2026年6月
数据库·sql·tdsql·pawsql·sql审核