您当前的位置: 首页 >  Python

壹小俊

暂无认证

  • 4浏览

    0关注

    885博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

第三课--python对mongo的使用

壹小俊 发布时间:2019-07-27 18:41:13 ,浏览量:4

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({})#查看数据find--查看所有(循环输出数据),find_one--查看一条(不需要循环)
print(data)
for i in data:
    print(i)
my_col.update_one(
    {'name':'hwj1'},
    {'$set':
         {'name':'hwj11'}
     }
)#修改update()--修改多条,update_one()--修改一条
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')

 

关注
打赏
1664335782
查看更多评论
立即登录/注册

微信扫码登录

0.0399s