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

相关推荐
✎ ﹏梦醒͜ღ҉繁华落℘5 小时前
单片机基础知识---stm32单片机的优先级
stm32·单片机·mongodb
麦聪聊数据6 小时前
数据服务化时代:企业数据能力输出的核心路径
数据库
shushangyun_6 小时前
2026年快消品B2B系统推荐:支持终端门店订货、促销政策自动化的工具?
java·运维·网络·数据库·人工智能·spring·自动化
DARLING Zero two♡6 小时前
【MySQL数据库】数据类型与表约束
数据库·mysql
曹牧7 小时前
Oracle EXPLAIN PLAN
数据库·oracle
BD_Marathon7 小时前
SQL学习指南——视图
数据库·sql
活宝小娜7 小时前
mysql详细安装教程
数据库·mysql·adb
贤时间7 小时前
codex 助力oracle ebs 开发
数据库·oracle
JLWcai202510097 小时前
铸造领域树脂砂轮|金利威多场景解决方案,20 + 配方覆盖全需求
mongodb·zookeeper·eureka·spark·rabbitmq·memcached·storm
秉承初心8 小时前
PostgreSQL 数据性能瓶颈突破实战
数据库·postgresql·oracle