import pymongofrom bson import ObjectIdimport jsonmongo_client=pymongo.MongoClient(host='127.0.0.1',port=27017) #连接数据库MONGO=mongo_client['xxx'] #找到所要查的表
"""#查询数据res=MONGO.xxx.find({}) #生成器for i in res: print(i)
res1=list(MONGO.xxx.find({}))print(res1)
res=MONGO.xxx.find_one({'id':20}) #去单个 用find_one# print(type(res),res.get('name'),res.get('_id'))res['_id']=str(res['_id'])print(res)res_json=json.dumps(res)print(res_json) #{"_id": "5c21f8ce902f3125d4f4c0ee", "id": 20, "name": 123}
res_obj=MONGO.xxx.find_one({'_id':ObjectId(res['_id'])})print(res_obj) #{'_id': ObjectId('5c21f8ce902f3125d4f4c0ee'), 'id': 20, 'name': 123}
# $or操作res=MONGO.xxx.find_one({'id':20})res1=list(MONGO.xxx.find({"$or":[{'id':20},{'name':123}]}))print(res1)"""
'''#增加数据res=MONGO.xxx.insert_one({'name':'qwe','age':13})print(res,res.inserted_id) #对象可以直接. res.inserted_id 5c21ff4311681e0858c20b91
res=MONGO.xxx.insert_many([{'name':'asd','age':12},{'name':'aaa','age':14}])print(res,res.inserted_ids) #存多个用res.inserted_ids'''
"""#修改数据
res=MONGO.xxx.update_one({'id':3},{'$set':{'id':6}})print(res,dir(res),res.raw_result)
res=MONGO.xxx.update_many({'id':2},{'$set':{'id':3}})print(res,dir(res),res.raw_result) #{'n': 38, 'nModified': 38, 'ok': 1.0, 'updatedExisting': True} #修改38个"""
"""#删除数据res=MONGO.xxx.delete_one({'id':6})res=MONGO.xxx.delete_many({'name':'qwe'})print(res,dir(res),res.raw_result)"""
"""#分页 limit 跳转 skip 排序 sortres=list(MONGO.xxx.find({"id":3}).limit(5))print(res,len(res))
res=list(MONGO.xxx.find({}).limit(5).skip(2))print(res,len(res))
#pymongo.DESCENDING res=list(MONGO.xxx.find({}).sort('id',-1).limit(5).skip(5))print(res,len(res))"""
"""#python 的update
res=MONGO.xxx.find_one({'id':3})print(res) #查看全部
#更改数据res.get('xxx')['shengao']=170res.get('xxx')['long']=20
#用对象来改数据MONGO.xxx.update_one({'_id':res.get('_id')},{'$set':res})res=MONGO.xxx.find_one({'id':3})print(res)
"""