b0116 数据库Mongodb 使用
说明
mongodb 5.0.9
linux centos 7.9, hc2108, 192.168.1.10, 安装路径 /opt
安装
参考 https://www.runoob.com/mongodb/mongodb-linux-install.html
1 从 https://www.mongodb.com/try/download/community 下载
2. 上传、解压,并移动到 /opt
/opt/mongodb-linux-x86_64-rhel70-5.0.9/ , 在根目录下 创建 data, log 目录。 目录结构如下
3. 配置环境变量
export MONGODB_HOME=/opt/mongodb-linux-x86_64-rhel70-5.0.9 export PATH=$PATH:$MONGODB_HOME/bin
source /etc/profile
4. 启动服务
mongod --dbpath \$MONGODB_HOME/data --logpath \$MONGODB_HOME/log/mongod.log --fork
下面的支持其他机器远程连接
mongod --dbpath $MONGODB_HOME/data --logpath $MONGODB_HOME/log/mongod.log --bind_ip=0.0.0.0,:: --fork
# 检查端口是否启动
netstat -anp|grep 27017
# 查看日志是否报错
cat \$MONGODB_HOME/log/mongod.log
#启动客户端,并输入命令
mongo
>
db.runoob.insert({x:10})
db.runoob.find()
# 停止服务端
mongod --dbpath \$MONGODB_HOME/data --logpath \$MONGODB_HOME/log/mongod.log --shutdown
使用
命令行客户端
https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-5.0.9.tgz /opt/mongodb-linux-x86_64-rhel70-5.0.9/bin export MONGODB_HOME=/opt/mongodb-linux-x86_64-rhel70-5.0.9 export PATH=$PATH:$MONGODB_HOME/bin conf mongdb.conf ------------------- port=27017 ###开放给所有客户端一定要带 ,:: bind_ip=0.0.0.0,:: # 运行任意机器连接,默认是 127.0.0.1 只允许本机连接 dbpath=$MONGODB_HOME/data # 数据库存放 logpath=$MONGODB_HOME/log/mongod.log # 日志文件 fork=true # 设置后台运行 auth=false # 开启认证 maxConns = 1000 objcheck = false logappend=false ----------------- $MONGODB_HOME/bin/mongod --config $MONGODB_HOME/conf/mongdb.conf # 启动服务端 mongod --dbpath $MONGODB_HOME/data --logpath $MONGODB_HOME/log/mongod.log --bind_ip=0.0.0.0,:: --fork netstat -anp|grep 27017 cat $MONGODB_HOME/log/mongod.log #启动客户端 mongo db.runoob.insert({x:10}) db.runoob.find() exit # 停止服务端 mongod --dbpath $MONGODB_HOME/data --logpath $MONGODB_HOME/log/mongod.log --shutdown > show dbs db db.runoob.insert({"site":"www.google.com","name":"Google"}) db.col.insert({ title: 'PHP 教程', description: 'PHP 是一种创建动态交互性站点的强有力的服务器端脚本语言。', by: '菜鸟教程', url: 'http://www.runoob.com', tags: ['php'], likes: 200 }) db.col.insert({title: 'Java 教程', description: 'Java 是由Sun Microsystems公司于1995年5月推出的高级程序设计语言。', by: '菜鸟教程', url: 'http://www.runoob.com', tags: ['java'], likes: 150 }) db.col.insert({title: 'MongoDB 教程', description: 'MongoDB 是一个 Nosql 数据库', by: '菜鸟教程', url: 'http://www.runoob.com', tags: ['mongodb'], likes: 100 }) db.col.find() db.col.find().limit(2) db.col.find().skip(2) db.col.find().skip(2) db.col.find().sort({"likes":1}) db.col.find({},{"title":1}) db.col.find({},{"title":1, _id:0}) db.col.find().pretty() use runoobdb; show tables; db.sites.find() db.sites2.find()
python
db_collection
# -*- coding: utf-8 -*- import pymongo myclient = pymongo.MongoClient("mongodb://hc2108:27017/") # 创建数据库 mydb = myclient["runoobdb"] dblist = myclient.list_database_names() print(dblist) mycol = mydb["sites"] collist = mydb.list_collection_names() print(collist) # 删除集合 # mycol.drop()
insert
# -*- coding: utf-8 -*- # !/usr/bin/python3 import pymongo # myclient = pymongo.MongoClient("mongodb://hc2108:27017/") myclient = pymongo.MongoClient("hc2108",27017) mydb = myclient["runoobdb"] mycol = mydb["sites"] # mydict = {"name": "RUNOOB", "alexa": "10000", "url": "https://www.runoob.com"} # # x = mycol.insert_one(mydict) # print(x) # # # 返回文档的id # print(x.inserted_id) mylist = [ {"name": "Taobao", "alexa": "100", "url": "https://www.taobao.com"}, {"name": "QQ", "alexa": "101", "url": "https://www.qq.com"}, {"name": "Facebook", "alexa": "10", "url": "https://www.facebook.com"}, {"name": "知乎", "alexa": "103", "url": "https://www.zhihu.com"}, {"name": "Github", "alexa": "109", "url": "https://www.github.com"} ] x = mycol.insert_many(mylist) # 输出插入的所有文档对应的 _id 值 print(x.inserted_ids)
# -*- coding: utf-8 -*- # !/usr/bin/python3 import pymongo myclient = pymongo.MongoClient("mongodb://hc2108:27017/") print(myclient) mydb = myclient["runoobdb"] print(mydb) mycol = mydb["site2"] print(mycol) # output """ MongoClient(host=['hc2108:27017'], document_class=dict, tz_aware=False, connect=True) Database(MongoClient(host=['hc2108:27017'], document_class=dict, tz_aware=False, connect=True), 'runoobdb') Collection(Database(MongoClient(host=['hc2108:27017'], document_class=dict, tz_aware=False, connect=True), 'runoobdb'), 'site2') """ mylist = [ {"_id": 1, "name": "RUNOOB", "cn_name": "菜鸟教程"}, {"_id": 2, "name": "Google", "address": "Google 搜索"}, {"_id": 3, "name": "Facebook", "address": "脸书"}, {"_id": 4, "name": "Taobao", "address": "淘宝"}, {"_id": 5, "name": "Zhihu", "address": "知乎"} ] x = mycol.insert_many(mylist) # 输出插入的所有文档对应的 _id 值 print(x.inserted_ids)
query
# -*- coding: utf-8 -*- # !/usr/bin/python3 import pymongo myclient = pymongo.MongoClient("mongodb://hc2108:27017/") mydb = myclient["runoobdb"] mycol = mydb["sites"] # 查询一条数据 x = mycol.find_one() print(x) print("---------") y = mycol.find() for m in y: print(m)
# -*- coding: utf-8 -*- # !/usr/bin/python3 import pymongo from bson.objectid import ObjectId myclient = pymongo.MongoClient("mongodb://hc2108:27017/") mydb = myclient["runoobdb"] mycol = mydb["sites"] for x in mycol.find({'name': 'Taobao'}, {}): print(x) # out {'_id': ObjectId('62c8379095e527e3e1d1377d')} for x in mycol.find({'name': 'Taobao'}): print(x) # out {'_id': ObjectId('62c8379095e527e3e1d1377d'), 'name': 'Taobao', 'alexa': '100', 'url': 'https://www.taobao.com'} for x in mycol.find({'_id': '62c8379095e527e3e1d1377d'}): print(x) # out nothing for x in mycol.find({"_id": "ObjectId('62c8379095e527e3e1d1377d')"}): print(x) # out nothing # 根据id 查询 for x in mycol.find({"_id": ObjectId('62c8379095e527e3e1d1377d')}): print(x) # out {'_id': ObjectId('62c8379095e527e3e1d1377d'), 'name': 'Taobao', 'alexa': '100', 'url': 'https://www.taobao.com'}
# -*- coding: utf-8 -*- # !/usr/bin/python3 import pymongo from bson.objectid import ObjectId myclient = pymongo.MongoClient("mongodb://hc2108:27017/") mydb = myclient["runoobdb"] mycol = mydb["sites"] for x in mycol.find({'name': 'Taobao'}): print(x) # out {'_id': ObjectId('62c8379095e527e3e1d1377d'), 'name': 'Taobao', 'alexa': '100', 'url': 'https://www.taobao.com'} for x in mycol.find({'name': 'Taobao'},{}): print(x) # out {'_id': ObjectId('62c8379095e527e3e1d1377d')} for x in mycol.find({}, {'name': 'Taobao'}): print(x) """ {'_id': ObjectId('62c8358886f5bf26c4026d21'), 'name': 'Taobao'} {'_id': ObjectId('62c835af5570d01ed39776aa'), 'name': 'Taobao'} {'_id': ObjectId('62c835b8a3bc3fdaee7dd5ac'), 'name': 'Taobao'} {'_id': ObjectId('62c8379095e527e3e1d1377d'), 'name': 'Taobao'} {'_id': ObjectId('62c8379095e527e3e1d1377e'), 'name': 'Taobao'} {'_id': ObjectId('62c8379095e527e3e1d1377f'), 'name': 'Taobao'} {'_id': ObjectId('62c8379095e527e3e1d13780'), 'name': 'Taobao'} {'_id': ObjectId('62c8379095e527e3e1d13781'), 'name': 'Taobao'} """
update
# -*- coding: utf-8 -*- # !/usr/bin/python3 import pymongo myclient = pymongo.MongoClient("mongodb://hc2108:27017/") mydb = myclient["runoobdb"] mycol = mydb["sites"] myquery = {"alexa": "10000"} newvalues = {"$set": {"alexa": "12345"}} # 修改 , 如果查找到的匹配数据多于一条,则只会修改第一条 # mycol.update_one(myquery, newvalues) # # # 输出修改后的 "sites" 集合 # for x in mycol.find(): # print(x) # 多条修改。 修改name R 开头的记录 myquery = {"name": {"$regex": "^R"}} newvalues = {"$set": {"alexa": "123"}} x = mycol.update_many(myquery, newvalues) print(x.modified_count, "文档已修改") for x in mycol.find(): print(x)
delete
# -*- coding: utf-8 -*- #!/usr/bin/python3 import pymongo myclient = pymongo.MongoClient("mongodb://hc2108:27017/") mydb = myclient["runoobdb"] mycol = mydb["sites"] myquery = {"name": "RUNOOB"} # 只删除一个 # mycol.delete_one(myquery) # 删除多个 myquery = {"name": {"$regex": "^R"}} x = mycol.delete_many(myquery) # 删除集合所有文档 # x = mycol.delete_many({}) print(x.deleted_count, "个文档已删除") # 删除后输出 for x in mycol.find(): print(x)
object id
# -*- coding: utf-8 -*- # !/usr/bin/python3 """ id操作 """ import pymongo from bson.objectid import ObjectId c = ObjectId('62c8379095e527e3e1d1377d') print(c) # 62c8379095e527e3e1d1377d print(type(c)) # <class 'bson.objectid.ObjectId'> print( c.generation_time ) # 2022-07-08 13:56:32+00:00 print( type(c.generation_time) ) # <class 'datetime.datetime'> s = str(c) print(s) # 62c8379095e527e3e1d1377d
参考
MongoDB教程 RUNOOB.COM 已经全部看完, 重要文档
计算机科学与技术/学习笔记 //0220629_大数据_mongodb学习.txt