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

相关推荐
不会就选b6 小时前
MySQL之视图
数据库·mysql
>no problem<6 小时前
基于cola5.0的基础设施层的多数据库切换方案思路
数据库·spring boot·mybatisplus·cola5.0·数据库迁移适配
OceanBase数据库官方博客6 小时前
OceanBase 赋能央国企:从发电到用电的全链路业务承载
数据库·oceanbase
瀚高PG实验室7 小时前
pgsql-ogr-fdw
数据库·postgresql·瀚高数据库·highgo
IvorySQL7 小时前
PostgreSQL 技术日报 (6月5日)|PG19 Beta1 上线,PGConf.PL 2026开启征稿
数据库·postgresql·区块链
abcy0712138 小时前
pycharm python sqlalchemy mysql增删改查实例csdn
数据库·oracle
无风听海8 小时前
IndexedDB 深度指南 浏览器中的事务型对象数据库
前端·数据库
咋吃都不胖lyh9 小时前
langgraph基础示例
数据库
胖胖胖胖胖虎9 小时前
SQL json_table 行转列方法
sql
网管NO.19 小时前
子查询进阶|EXISTS/IN/ANY/ALL,优化查询效率
数据库·sql