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

相关推荐
一颗宁檬不酸1 小时前
文件管理知识点
数据库
1 小时前
达梦数据库-事务
数据库·达梦数据库·dm
网硕互联的小客服2 小时前
MYSQL数据库和MSSQL数据库有什么区别?分别适用于什么脚本程序?
数据库·mysql·sqlserver
weixin_462446233 小时前
【原创实践】python 获取节假日列表 并保存为excel
数据库·python·excel
RPA 机器人就找八爪鱼3 小时前
RPA 赋能银行数字化转型:四大核心应用场景深度解析
数据库·人工智能·rpa
掂掂三生有幸3 小时前
使用openGauss搭建一个监狱管理系统
数据库
VX:Fegn08953 小时前
计算机毕业设计|基于Java人力资源管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·后端·课程设计
siriuuus3 小时前
Redis 安装、多实例部署、主从复制及 Cluster 实践
数据库·redis·centos
Polaris_GQ4 小时前
Navicat连接Oracle数据库报错:12514问题
数据库
老华带你飞4 小时前
健身房|基于springboot + vue健身房管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端