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

相关推荐
m0_624578593 分钟前
MySQL主从复制支持跨版本吗_不同版本间同步的注意事项
jvm·数据库·python
2401_8714928535 分钟前
如何在 React Router v6 中正确配置多路由组件显示
jvm·数据库·python
Fᴏʀ ʏ꯭ᴏ꯭ᴜ꯭.1 小时前
《redis-cluster 集群部署完全手册(含扩容+缩容)》
数据库·redis·缓存
snow@li1 小时前
数据库-MongoDB:常用语法 / MongoDB 核心知识技能梳理
数据库·mongodb
想躺平的小羊2 小时前
关于金额在数据库设置类型问题
数据库
zhangchaoxies2 小时前
MySQL触发器能否监控特定用户操作_结合审计功能实现分析
jvm·数据库·python
chushiyunen2 小时前
faiss向量检索库(并非向量数据库)
数据库·faiss
qq_413502022 小时前
如何解决ORA-12518监听程序无法分配进程_内存耗尽与PGA溢出
jvm·数据库·python
Carsene2 小时前
第一章:为什么我们需要“类型安全”的 SQL DSL 框架?
java·sql
Mr_pyx3 小时前
Java 注解(Annotation)详解:从基础到 APT 实战
java·数据库·sqlserver