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

相关推荐
鹿角片ljp1 小时前
苍穹外卖 day05:店铺营业状态设置与Redis入门实战
数据库·redis·缓存
m0_743470372 小时前
使用Python进行PDF文件的处理与操作
jvm·数据库·python
Demon_Hao2 小时前
JAVA通过Redis实现Key分区分片聚合点赞、收藏等计数同步数据库,并且通过布隆过滤器防重复点赞
java·数据库·redis
掘根2 小时前
【微服务即时通讯】消息转发子服务
数据库·oracle
喜欢喝果茶.2 小时前
SQL 预处理
数据库·sql
数据科学小丫4 小时前
Python 数据存储操作_数据存储、补充知识点:Python 与 MySQL交互
数据库·python·mysql
Knight_AL4 小时前
Nacos 启动问题 Failed to create database ’D:\nacos\nacos\data\derby-data’
开发语言·数据库·python
xianjian09125 小时前
MySQL 的 INSERT(插入数据)详解
android·数据库·mysql
知识分享小能手5 小时前
MongoDB入门学习教程,从入门到精通,MongoDB入门指南 —— 知识点详解(2)
数据库·学习·mongodb
what_20186 小时前
PostgreSQL 索引
数据库·postgresql