使用程序操作mongodb
mongodb可以使用java、python、php等语言去操作
运维使用Python居多,介绍使用python操作Mongodb数据库
使用python操作mongodb,需要使用pip安装pymongo模块
yum install epel-release -y
yum install python2-pip -y
pip install pymongo
连接代码,单实例的连接代码
import pymongo client = pymongo.MongoClient( '127.0.0.1', 27017 ) shijiange=client.shijiange myuser = shijiange.myuser for item in myuser.find(): print(item)
pymongo副本集的连接代码,代码支持自动切换
import pymongo client = pymongo.MongoClient( ['127.0.0.1:27017', '127.0.0.1:27018', '127.0.0.1:27019'] ) shijiange = client.shijiange myuser = shijiange.myuser myvar = {'age':20, 'name': 'shijiange'} myuser.insert(myvar) for item in myuser.find(): print(item)
副本集的搭建配置文档
systemLog: destination: file logAppend: true path: /data/mongodb/27017/mongodb.log storage: dbPath: /data/mongodb/27017/ journal: enabled: true processManagement: fork: true net: port: 27017 bindIp: 0.0.0.0 replication: replSetName: shijiange
副本集的mongo命令
config = { _id:"shijiange", members:[
{_id:0,host:"127.0.0.1:27017"},
{_id:1,host:"127.0.0.1:27018"},
{_id:2,host:"127.0.0.1:27019"}]
}
use admin
rs.initiate( config )