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

相关推荐
3095566666 小时前
股票接口重试怎么分类:正常、空数组与错误响应的幂等处理
java·大数据·开发语言·数据库·php·api接口·股票数据api接口
城北徐宫8 小时前
MySQL基础与库、表操作
数据库·mysql
码完就睡9 小时前
Redis——初识 Redis
数据库·redis·缓存
飞花漫卷,情随岁迁13 小时前
网络数据包转发与内核机制:小白概念科普
linux·运维·网络·数据库·mysql·oracle·智能路由器
wangxiaoxuan21714 小时前
大模型怎样调用机器人能力:目标落地、工具调用与执行反馈
数据库·机器人·php
数据世界117 小时前
从立项选品到竞争情报:医药人查询国内品种格局数据的难点与5.0版结构化整理
大数据·数据库·人工智能
AI 编程助手GPT19 小时前
GPT 写 SQL:避免订单金额被重复统计
jvm·人工智能·sql·gpt
AAA修煤气灶刘哥19 小时前
数据搬到另一朵云,小红书的训练任务怎么接着读?
数据库·后端·架构