mongodb数据库
Python3 操作Mongodb数据库安装
安装
pip3 install pymongo
运行环境:
Python3.6.2
Mongodb3.0
Pymongo3.6.1
获取集合
from pymongo import MongoClient client = MongoClient('mongodb://localhost:27017') db = client.get_database('python') mycol = db.get_collection('mycol')
删除集合
mycol.drop()
查看所有文档
for doc in mycol.find():
print(doc)
获取文档的个数
mycol.count()
插入一个文档
mycol.insert_one({'title':'t1'})
插入多个文档
docs = []
docs.append({'title':'t2'})
docs.append({'title':'t3'})
mycol.insert_many(docs)
替换文档
result = mycol.replace_one({'title':'t1'}, {'title':'t2'})
print('matched_count=' + str(result.matched_count))
print('modified_count=' + str(result.modified_count))
更新一个文档
result = mycol.update_one({'title':'t2'}, {'$set':{'title':'title0'}}) print('matched_count=' + str(result.matched_count)) print('modified_count=' + str(result.modified_count))
更新多个文档
result = mycol.update_many({'title':'t2'}, {'$set':{'title':'title0'}})
print('matched_count=' + str(result.matched_count))
print('modified_count=' + str(result.modified_count))
删除一个文档
result = mycol.delete_one({'title':'title0'})
print('deleted_count=' + str(result.deleted_count))
删除多个文档
result = mycol.delete_many({'title':'title0'})
print('deleted_count=' + str(result.deleted_count))
Great works are not done by strength, but by persistence!