第一大题:
1.清空并创建school
数据库,并查看有哪些集合
use school;
db.dropDatabase();
use school;
show tables;
2.创建三年级二班(class_3_2), 三年级五班(class_3_5), 三年级八班(class_3_8)共3个班,
并给每个班随机添加 10 名学生, 包含学生的姓名(s_name), 学生的性别(s_sex), 学生的年龄(s_sex),学生的爱好(s_habit)
for(class_index in (classes ='class_3_2', 'class_3_5', 'class_3_8'])) {
for (var i = 1; i <= 10; i++) {
db[classes[class_index]].insert({
"s_name": "zhoujielun" + i,
"s_sex": Math.round(Math.random() * 10) % 2,
"s_age": Math.round(Math.random() * 4) + 10,
"s_habit": ["dance", "eat"]
});
}
}
mongorestore -d school --dir D:\mongodb\output\school -u okk --authenticationDatabase admin
-d 指恢复后的数据库
--dir 指数据来源
-u 用户名
--authenticationDatabase admin 授予权限
3.查看三年级二班中的所有学生
db.getCollection('class_3_2').find() ---下面只用这个方式写
或
db.class_3_2.find()
4.查看三年级二班中所有年龄是 11岁的学生
db.getCollection('class_3_2').find({"s_age": 11})
5查看三年级二班中所有年龄大于 12 岁的学生
db.getCollection('class_3_2').find({"s_age": {$gt: 12}})
6查看三年级二班中所有年龄大于 12岁并且小于 14岁的学生
db.getCollection('class_3_2').find({"s_age": {$gt: 12, $lt: 14}})
7查看三年级二班中所有年龄大于 12 岁并且性别值为0
的学生
db.getCollection('class_3_2').find({"s_age": {$gt: 12}, "s_sex": 0})
8查看三年级二班中所有年龄小于 12 岁并且大于13岁的学生
db.getCollection('class_3_2').find({$or: [{"s_age": {$lt: 12}}, {"s_age": {$gt: 13}}]})
9查看三年级二班中所有年龄是11 岁或 13 岁的学生
db.getCollection('class_3_2').find({"s_age": {$in: [11, 13]}})
10.查看三年级二班中所有姓名带zhoujielun1
字符的学生
db.getCollection('class_3_2').find({"s_name": {$regex: "zhoujielun1"}})
11.查看三年级二班中所有姓名带zhoujielun1
和zhoujielun2
字符的学生
db.getCollection('class_3_2').find({"s_name": {
$in: [new RegExp("zhoujielun1"), new RegExp("zhoujielun2")]
}})
12.三年二班,修改名为zhoujielun7
的学生,年龄为9 岁,兴趣爱好为 跳舞和画画;
db.getCollection('class_3_2').update({"s_name": "zhoujielun7"}, {$set: {"s_age": 8, "s_habit": ["dance", "drawing"]}})
- 三年二班中,追加
zhoujielun7
学生兴趣爱好唱歌;
<