IT源码网

python中的pymongo连接脚本

leader 2020年04月10日 编程语言 586 0

author: headsen chen

date: 2019-04-12  17:39:12

 

先安装python3,pymongo

[root@localhost mnt]# cat /root/python-install.sh  
#!/bin/bash 
yum -y install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel 
mkdir -p /usr/local/python3 
cd /mnt 
wget https://www.python.org/ftp/python/3.6.1/Python-3.6.1.tgz 
tar -zxvf Python-3.6.1.tgz 
cd Python-3.6.1 
./configure --prefix=/usr/local/python3 
make && make install 
ln -s /usr/local/python3/bin/python3 /usr/bin/python3 
echo "PATH=$PATH:/usr/local/python3/bin"  >>/etc/profile 
echo "export PATH " >>/etc/profile 
source /etc/profile 
python3 -V

安装 pip

/usr/local/python3/bin/pip3 install --upgrade pip 
/usr/local/python3/bin/pip3 install pymongo

安装mongodb

[root@localhost mnt]# cat mongo-install.sh  
curl -O https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.0.6.tgz 
tar fx mongodb-linux-x86_64-3.0.6.tgz  
mv mongodb-linux-x86_64-3.0.6 /usr/local/mongodb 
export PATH=/usr/local/mongodb/bin:$PATH

[root@localhost mnt]# echo "export PATH=/usr/local/mongodb/bin:$PATH" >>/etc/profile;source /etc/profile # 让mongo命令生效到环境变量里边,

pymongo插入多行数据脚本

import pymongo 
import datetime 
def main():
myclient = pymongo.MongoClient('mongodb://abc.dddd.com:27017') # 连接地址 myclient.admin.authenticate("useraaaaa","passwordaaaa",mechanism='SCRAM-SHA-1') # 用户名,密码,连接机制 mydb = myclient["db_value"] # 数据库名 mycol = mydb["Collection_name"] # 表名 for i in range(98): invite_record = {"Code":"Event008","Name":"邀请好友注册", "Target":"","UserId":169203, "Value":10, "CreateTime": datetime.datetime.now().utcnow()} x = mycol.insert_one(invite_record) # insert_one :pymongo 自带的一次插入一行记录的方法 print(x.inserted_id) main()
评论关闭
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!