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

相关推荐
梦幻通灵15 小时前
Mysql字段判空实用技巧
android·数据库·mysql
酸菜牛肉汤面17 小时前
23、varchar与char的区别
数据库
AI题库17 小时前
PostgreSQL 18 从新手到大师:实战指南 - 2.5 Serverless PostgreSQL
数据库·postgresql·serverless
IT技术分享社区17 小时前
数据库实战:MySQL多表更新JOIN操作的底层原理与性能调优指南
数据库·mysql·程序员
廋到被风吹走17 小时前
【数据库】【Oracle】分区表与大表设计
数据库·oracle
UrSpecial18 小时前
InnoDB存储引擎
数据库·mysql
gjc59218 小时前
MySQL隐蔽 BUG:组合条件查询无故返回空集?深度排查与规避方案
android·数据库·mysql·bug
❀͜͡傀儡师18 小时前
docker部署PostgreSQL数据库的监控和管理工具
数据库·docker·postgresql
a1879272183119 小时前
MySQL 事务
数据库·mysql·事务·mvcc·acid·readview·可见性判断算法
梨落秋霜19 小时前
Python入门篇【元组】
android·数据库·python