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

相关推荐
努力成为AK大王1 小时前
并发编程的核心挑战、优化方案与核心知识点总结
java·开发语言·数据库
En^_^Joy2 小时前
Django开发:模板系统入门指南
数据库·django·sqlite
无关86882 小时前
Redis Bitmaps 用户签到系统设计方案
数据库·redis·缓存
江华森2 小时前
FastAPI 极速开发指南 — 从零到生产级 API 实战
数据库·fastapi
老纪4 小时前
Redis分布式锁进第九零篇
数据库·redis·分布式
haven-8524 小时前
MySQL事务ACID、隔离级别、MVCC、幻读解决
数据库·mysql
小高学习java4 小时前
事务的边界问题,如何判断数据回滚时机。
java·数据库·后端
葡萄皮sandy5 小时前
NestJS + Mongoose 全栈开发面试总结
mongodb·面试
迷枫7125 小时前
【无标题】
数据库
TDengine (老段)5 小时前
TDengine 扫描算子 — TableScan、TagScan 与下推优化
大数据·数据库·物联网·时序数据库·tdengine·涛思数据