利用python操作mongodb需要导入pymongo库
pip install pymongo
1、连接mongodb
import pymongo
client = pymongo.MongoClient(host='localhost',port=27017)
host为mongo的ip地址,port为端口号,如果不传port则默认为27017
2、连接数据库
db=client.test 或 db=client['test']
test为数据库名,这儿只是以test举例
3、对集合操作,假设集合名为citys
collection = db.citys
3.1 对citys插入数据
字典的形式
city1 = {'id':1,
'name':'beijing',
'people_number':3000000,
'old_people_number':10000}
beijing=collection.insert(city1)
3.2对citys查询
find_beijing = collection.find({'name':'beijing'})
3.3修改数据
update_beijing = collection.update_one({'name':'beijing'},{'$set':{'name':'shanghai'}})
update_one是只更新符合条件的第一条数据,update_many为更新符合的条件的所有数据,用法和update_one一样
3.4删除
remove_beijing = collection.remove({'name':'beijing'})
除此之外还有delete_one()和delete_many()两种方法,和修改数据中的one与many一样
4、关闭数据库的链接
client.close()
基本操作如上所述。对于mongodb的其他操作参考mongodb操作的两篇文章:
用法和上述中对集合的增删改查操作类似