python 操作 mongodb
参考网址:API: http://api.mongodb.com/python/3.4.0/api/index.html
1、安装mongodb
略过
2、查看mongodb数据
usr/local/mongodb/bin/mongo ip:port
> show dbs
db_anchor 0.000GB
db_gss 0.001GB
local 0.273GB
> use db_gss
switched to db db_gss
> show tables
tbl_anchor_hotinfo
tbl_crs_intranet_info
tbl_crs_proxy_info
tbl_game_anchor_oplist
tbl_hall_stats
tbl_proxy_server_info
tbl_robot_stats
tbl_spread_anchor_info
> db.tbl_hall_stats.find()
{ "_id" : ObjectId("586e4fbf252a18ff65ce9e97"), "hall_id" : 1000, "anchorid" : 0, "anchorname" : "", "aurl" : "", "checkstate" : 0, "cversion" : "", "ip" : [ { "ip" : "192.168.9.151", "isp" : 3, "port" : 5002, "property" : 0 } ], "livestate" : 4, "photonum" : 0, "service" : 1, "stype" : 1, "usercount" : 0, "anchorstate" : 0, "anchortitle" : "秦泽 真开播啦", "position" : "北京市", "familyid" : 0, "familyname" : "", "time" : "1499251410", "regionlimit" : 0, "nobility" : 0, "intranet" : "192.168.9.151", "port" : 5002 }
3、安装pymongo库
sudo pip install pymongo
python
>>> import pymongo
如果没有错误代表成功了
3、使用 pymongo
#连接mongo数据库
client = MongoClient(ip, port)
#指定databasename
db = client.db_gss
#获取指定database下的非系统的所有集合(表名)
collection = db.collection_names(include_system_collections=False)
#获取表的操作句柄
posts = db.tbl_hall_stats
#构建数据
new_post = { "hall_id" : 2056, "anchorid" : 0, "anchorname" : "", "aurl" : "", "checkstate" : 0, "cversion" : "", "ip" : [ { "ip" : "192.168.9.151", "isp" : 3, "po rt" : 5025, "property" : 0 } ], "livestate" : 4, "photonum" : 0, "service" : 1, "stype" : 1, "usercount" : 0, "anchorstate" : 0, "anchortitle" : 'kaibole', "position" : "Beijing", "familyid" : 0, "familyname" : "", "time" : "1496211667", "regionlimit" : 0, "nobility" : 0, "intranet" : "192.168.9.151", "port" : 5025 }
#插入单条数据
posts.insert_one(new_post)
client.close()