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

相关推荐
djjjx.4 小时前
Mysql数据库基础篇(八):详细讲解复合查询、多表查询、自连接、多行、多列子查询与合并查询
数据库·mysql
CoderYanger8 小时前
Java EE 进阶:9.MyBatis 操作数据库(进阶)(第八弹):MyBatis Generator
java·数据库·spring boot·spring·java-ee·tomcat·mybatis
MSTcheng.9 小时前
【MySQL】MySQL数据库——表的操作
数据库·mysql·adb
Yeats_Liao10 小时前
物联网平台MongoDB实战|(一)为什么选择MongoDB
数据库·物联网·mongodb
ZhengEnCi10 小时前
覆盖索引是什么:用借书和外卖看懂回表这件事
sql·mysql·postgresql
鹤落晴春11 小时前
MySQL日志梳理
运维·数据库·mysql
五彩小白12 小时前
Redis的过期删除和内存淘汰机制
数据库·redis·缓存
学长毕设12 小时前
基于SpringBoot 博物馆文物租赁及修复管理系统-附源码
大数据·数据库·spring boot
apcipot_rain12 小时前
C++转Java日记(14)
数据库
CoderYanger12 小时前
Java EE 进阶:10. MyBatis-Plus使用(第一弹)
java·spring boot·后端·sql·spring·java-ee·mybatis