mongodb作业

1.创建一个数据库 名字grade

powershell 复制代码
use grade

2.数据库中创建一个集合名字 class

powershell 复制代码
db.createCollection("class")

3.集合中插入若干数据

powershell 复制代码
db.class.insert([{name:"zhang",age:10,sex:'m',hobby:['a','b','c']}])

4.查找

查看班级所有人信息

powershell 复制代码
db.class.find()

查看班级中年龄为8岁的学生信息

powershell 复制代码
db.class.find({age:8})

查看年龄大于10岁的学生信息

powershell 复制代码
db.class.find({age:{$gt:10}})

查看年龄在 4---8岁之间的学生信息

powershell 复制代码
db.class.find({age:{$gt:4,$lte:8}})

找到年龄为6岁且为男生的学生

powershell 复制代码
db.class.find({age:6,sex:'m'})

找到年龄小于7岁或者大于10岁的学生

powershell 复制代码
db.class.find({$or:[age:{$lt:7},age:{$gt:10}]})

找到年龄是8岁或者11岁的学生

powershell 复制代码
db.class.find({age:{$in:[8,11]}})

找到兴趣爱好有两项的学生

powershell 复制代码
db.class.find({hobby:{$size:2}})

找到兴趣爱好有draw的学生

powershell 复制代码
db.class.find({hobby:"draw"})

找到既喜欢画画又喜欢跳舞的学生

powershell 复制代码
db.class.find({hobby:{$all:["draw","dance"]}})

统计爱好有三项的学生人数

powershell 复制代码
db.class.find({hobby:{$size:3}}).count()

找出本班年龄第二大的学生

powershell 复制代码
db.class.find().sort({age:-1}).skip(1).limit(1)

查看学生的兴趣范围

powershell 复制代码
db.class.distinct('hobby')

将学生按年龄排序找到年龄最大的三个

powershell 复制代码
db.class.find().sort({age:-1}).limit(3)

删除所有 年级大于12或者小于4岁的学生

powershell 复制代码
remove({$or:[{age:{$gt:12}},{age:{$lt:4}}]})

5.增加、更新、删除、统计

将小红的年龄变为8岁 兴趣爱好变为 跳舞 画画

powershell 复制代码
{$set:{age:8,hobby:['dance','draw']}}

追加小明兴趣爱好 唱歌

powershell 复制代码
{$push:{hobby:'sing'}}

小王兴趣爱好增加 吹牛 打篮球

powershell 复制代码
{$pushAll:{hobby:['吹牛','basketball']}}

小李增加爱好,跑步和唱歌,但是不要和以前的重复

powershell 复制代码
{$addToSet:{hobby:{$each:['running','sing']}}}

该班所有同学年龄加1

powershell 复制代码
update({},{$inc:{age:1}},false,true)

删除小明的sex属性

powershell 复制代码
{$unset:{sex:0}}

删除小李兴趣中的第一项

powershell 复制代码
{$pop:{hobby:-1}}

将小红兴趣中的画画爱好删除

powershell 复制代码
{$pull:{hobby:'draw'}}

增加分数域 score:{'chinese':88,'english':78,'math':98}

按照性别分组统计每组人数

powershell 复制代码
 aggregate({$group:{_id:'$sex',num:{$sum:1}}})

按照姓名分组,过滤出有重名的同学

powershell 复制代码
aggregate([{$group:{_id:'$name',num:{$sum:1}}},{$match:{num:{$gt:1}}}])

统计每名男生的语文成绩

powershell 复制代码
aggregate([{$match:{sex:'m'}},{$project:{_id:0,name:1,'score.chinese':1}}])

将女生按照英语分数降序排列

powershell 复制代码
aggregate([{$match:{sex:'w'}},{$sort:{'score.english':-1}}])
相关推荐
寂柒11 分钟前
信号量——基于环形队列的生产消费模型
linux·ubuntu
林姜泽樾4 小时前
Linux入门第十二章,创建用户、用户组、主组附加组等相关知识详解
linux·运维·服务器·centos
xiaokangzhe5 小时前
Linux系统安全
linux·运维·系统安全
feng一样的男子5 小时前
NFS 扩展属性 (xattr) 提示操作不支持解决方案
linux·go
Highcharts.js6 小时前
Highcharts React v4.2.1 正式发布:更自然的React开发体验,更清晰的数据处理
linux·运维·javascript·ubuntu·react.js·数据可视化·highcharts
c++之路6 小时前
Linux网络协议与编程基础:TCP/IP协议族全解析
linux·网络协议·tcp/ip
Charlie__ZS7 小时前
Ubuntu 22.04新建用户,并赋予管理权限
linux·os·ubuntn
LCG元7 小时前
固件加密保护:STM32F2 Flash读写保护,AES软件加密实现
stm32·嵌入式硬件·mongodb
keep intensify8 小时前
康复训练 5
linux·c++
OxyTheCrack8 小时前
【C++】详细拆解std::mutex的底层原理
linux·开发语言·c++·笔记