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

相关推荐
Lucifer三思而后行14 小时前
中标麒麟 NeoKylin V7 一键安装 Oracle 12CR2 ASM(240116)
数据库·oracle
m0_7349497920 小时前
MySQL如何配置定时清理过期备份文件_find命令与保留周期策略
jvm·数据库·python
m0_5145205720 小时前
MySQL索引优化后性能没提升_通过EXPLAIN查看索引命中率
jvm·数据库·python
NaMM CHIN20 小时前
sql实战解析-sum()over(partition by xx order by xx)
数据库·sql
不瘦80斤不改名21 小时前
深入浅出 MySQL(一):一文理清 SQL 核心规范与五大分类
数据库·sql·mysql
woniu_buhui_fei21 小时前
MySQL知识整理二
数据库·mysql
Polar__Star1 天前
如何在 AWS Lambda 中正确使用临时凭证生成 S3 预签名 URL
jvm·数据库·python
Lucifer三思而后行1 天前
zCloud 中 Oracle 实例状态未知问题记录
数据库·oracle
island13141 天前
最详细VMware Workstation 17 上安装 Ubuntu 系统
linux·数据库·ubuntu
卢傢蕊1 天前
MongoDB
数据库·mongodb