mongodb的连接与使用
废话不多说直接上代码
# coding=utf-8
from pymongo import MongoClient
# 实例化和插入
class TestMongo():
def __init__(self):
conn = MongoClient(host='127.0.0.1',port=27017) # mongo的地址和端口号
self.collection = conn['test']['t3'] #test是数据库,t3是集合名
def insert_demo(self): #插入数据的函数
ret = self.collection.insert({'name':'python','age':23})
print(ret)
def insert_many(self):
list = [{'name':'test{}'.format(i),'age':i} for i in range(10)]
ret_list = self.collection.insert_many(list)
for temp in ret_list.inserted_ids:
print(temp)
# 查询和更新
def find_one(self):
t = self.collection.find_one({'name':'test10'})
print(t)
def find_many(self):
t = self.collection.find({'name':'test10'})
for i in t:
print(i)
for i in t:
print(i) #打印为空,因为当前的游标已在最后一个了,所以无法打印
def try_update_one(self):
self.collection.update_one({'name':'test10'},{'$set':{'name':'new_test10'}})
def try_update_many(self):
self.collection.update_many({'name':'test10'},{'$set':{'name':'new_test10'}})
def try_delete_one(self):
self.collection.delete_one({'name':'test8'})
print('删除成功')
if __name__ == '__main__':
mg = TestMongo()
# mg.insert_demo()
# mg.insert_many()
# mg.find_one()
# mg.find_many()
mg.try_delete_one()
print('-'*100)
mg.find_many()
这是我今天闲暇时间写的,本地运行还OK,希望看客们多交流交流^_&