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

相关推荐
隔壁老登1 分钟前
查询hive指定数据库下所有表的建表语句并生成数据字典
数据库·hive·hadoop
sekaii18 分钟前
ReDistribution plan细节
linux·服务器·数据库
焱焱枫1 小时前
自适应SQL计划管理(Adaptive SQL Plan Management)在Oracle 12c中的应用
数据库·sql·oracle
2301_793069821 小时前
Spring Boot +SQL项目优化策略,GraphQL和SQL 区别,Spring JDBC 等原理辨析(万字长文+代码)
java·数据库·spring boot·sql·jdbc·orm
hhw1991121 小时前
spring boot知识点5
java·数据库·spring boot
ITPUB-微风2 小时前
功能开关聚合对象实践:提升金融领域的高可用性
网络·数据库·金融
去看日出2 小时前
Linux(centos)系统安装部署MySQL8.0数据库(GLIBC版本)
linux·数据库·centos
Hanyaoo2 小时前
为什么mvcc中?m_ids 列表并不等同于 min_trx_id 和 max_trx_id 之间的所有事务 ID
数据库
偏右右3 小时前
PL/SQL 异常处理
数据库·sql·oracle
利瑞华3 小时前
Redis 存在线程安全问题吗?为什么?
数据库·redis·安全