python3链接mongodb需要安装包,使用pip安装。
import pymongo
client = pymongo.MongoClient()
mydb = client['new_163']
mycol = mydb['items']
data = mycol.find()
print(data)
for i in data:
print(i['_id'])
看案例
import pymongo
client = pymongo.MongoClient()
my_db = client['hwj']
my_col = my_db['stu']
my_col.insert_many([
{'_id':1,'name':'hwj1','age':181},
{'_id':2,'name':'hwj2','age':182},
{'_id':3,'name':'hwj3','age':183}
])
data = my_col.find({})
print(data)
for i in data:
print(i)
my_col.update_one(
{'name':'hwj1'},
{'$set':
{'name':'hwj11'}
}
)
my_col.remove()
import pymongo
class classMongo(object):
'''
初始化mongo
'''
def __init__(self,db,collection):
self.client = pymongo.MongoClient()
self.db = self.client[db]
self.collection = self.db[collection]
'''
查询
'''
def mFind(self,where=False):
if where!=False:
data = self.collection.find({where})
else:
data = self.collection.find()
return data
def mFindOns(self,where=False):
if where!=False:
data = self.collection.find_one({where})
else:
data = self.collection.find_one()
return data
'''
插入
'''
def mInsert(self,data,only_one=True):
if only_one:
bool = self.collection.insert_one(data)
else:
bool = self.collection.insert_many(data)
return bool
'''
移除
'''
def mRemove(self,where=True):
if where:
bool = self.collection.remove(where)
else:
bool = self.collection.remove()
return bool
'''
修改
'''
def mUpdate(self,where,only_one=True):
if only_one:
bool = self.collection.update_one(where)
else:
bool = self.collection.update(where)
return bool
m = classMongo('hwj','stu')