You need to first install Python and MongoDB, where MongoDB's installation references the previous blog post.
In the official parlance, it is recommended to use the PIP to install the MongoDB python driver Pymongo
First need to install PIP, may need to install Python-dev
sudo apt-get install Python-dev pip
Install the MongoDB python driver
Pip Install Pymongo
Update Pymongo
Pip--upgrade Pymongo
Use the following Python program mongodb_test.py test
#!/usr/bin/env python
#encoding: utf-8
import pymongo
import random
conn = Pymongo. Connection ("127.0.0.1", 27017)
db = Conn.mydb #you must create the database MyDB in advance
#db. Authenticate ("Tao Yx "," 123 ") #用户认证
db.user.drop () #删除集合user
db.user.save ({' id ': 1, ' name ': ' Peter ', ' sex ': ' Male '}) #插入一条数据
#循环插入一组数组
for I in range (2):
name = Random.choice ([' Steve ', ' Tom ', ' Owen ', ' Sally ', ' Alice '])
sex = Rand Om.choice ([' Male ', ' female '])
Db.user.insert ({' id ': I, ' name ': Name, ' Sex ': sex})
content = Db.user.find ()
#打印所有数据 for
i in content:
print I
The test results are as follows