题目如下:

 

 

MongoDB服务端默认的端口号:27017

切换数据库的命令:use+数据库名

MongoDB的配置文件名:mongodb.conf

只允许本地访问将配置文件中的Bind_ip改为:0.0.0.0

MongoDB中数据库、集合和文档三个定义的关系:一个数据库由多个集合组成,一个集合由多个文档组成。

创建一个名叫"Bigdata"的数据库

执行以下命令

use Bigdata

 

 

在Bigdata数据库创建名为"data1901"的一个集合

执行以下命令

db.createCollection("data1901")

 

 通过

show collections

来查看

集合已经创建完成 

集合插入一条文档,文档包含name,ID, gender和major四个键值对

执行以下命令

db.data1901.insert({"name":"yourname"})

查看是否写入

db.data1901.find()

 

依次执行

db.data1901.insert({"ID":19322631})
db.data1901.insert({"gender":"male"})
db.data1901.insert({"major":"Data science"})

 新建ComputerScience数据库和students集合

 将数据指定进x

x=[{"_id":"1001","name":"程明","sex":"男","age":19,"major":"计算机应用技术","credits":52,score:92}, {"_id":"1002","name":"刘萍","sex":"女","age":18,"major":"移动应用开发","credits":51,score:88}, {"_id":"1003","name":"张静","sex":"女","age":20,"major":"计算机应用技术","credits":48,score:96}, {"_id":"1004","name":"陈好","sex":"女","age":20,"major":"软件技术","credits":53,score:97}, {"_id":"1005","name":"施行","sex":"男","age":20,"major":"计算机应用技术","credits":54,score:60} ,
{"_id":"1006","name":"刘文平","sex":"女","age":18,"major":"软件技术","credits":50,score:86}, {"_id":"1007","name":"李德胜","sex":"男","age":20,"major":"计算机应用技术","credits":55,score:95}, {"_id":"1008","name":"苏锦州","sex":"男","age":18,"major":"移动应用开发","credits":50,score:70}, {"_id":"1009","name":"张文杰","sex":"女","age":20,"major":"软件技术","credits":53,score:40}, {"_id":"1010","name":"王林","sex":"男","age":18,"major":"移动应用开发","credits":47,score:87}

 

将x插入进students 

 查询计算机应用技术和软件技术专业成绩大于90分的学生姓名、性别、专业和成绩

db.students.find({$or:[{"major":"软件技术","score":{"$gt":90}},{"major":"计算机应用技术","score":{"$gt":90}}]},{"name":1,"sex":1,"major":1,"score":1})

 

将张静的专业(major)修改为“数据科学与大数据技术”

db.students.update({"name":"张静"},{$set:{"major":"数据科学与大数据技术"}})

 

给软件技术专业的所有女生添加一个字段course,值为BigData

db.students.update({"major":"软件技术","sex":"女"},{$addToSet:{"course":"BigData"}},false,true)

 

查询所有男生的姓名,性别,年龄信息,并且按照年龄的降序显示

db.students.find({"sex":"男"},{"name":1,"sex":1,"age":1}).sort({"age":-1})

 

查找所有学生信息,按照专业升序,年龄降序排列

db.students.find().sort({"age":-1},{"major":1})

 

利用pymongo读取虚拟机中mongo数据库现有的所有数据库名称,并将读取的所有数据库名称赋值给yourname

pip安装 pymongo:

python3 -m pip3 install pymongo

在pycharm中连接数据库

import pymongo
myclient = pymongo.MongoClient("mongodb://root:123@192.168.17.130:27017/admin")
yourname = myclient.list_database_names()
print(yourname)

创建有权限的用户

用户名是yzy密码是2631

先修改sudo vim /etc/mongodb.conf为

#noauth = true

auth = true

如图所示

然后创建对所有库可以读写的yzy用户密码是2631 ,使用dba来管理

 创建用户

db.createUser({user:'yzy', pwd:'2631', roles:[{role: 'readWriteAnyDatabase', db:'admin'}]})

给yzy用户给予读写权限

 通过show users查看已创建用户

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐