诚意
诚意如你,当一诚的态度对待

导航

 

引言:

  PyMongo是Python操作MongoDB的工具,和pymysql操作MySQL的功能一样

  

pip3 install pymongo  #安装模块包

  

 一:模块使用-操作mongodb

import  pymongo
import json
from bson import ObjectId

mongoclient = pymongo.MongoClient(host='127.0.0.1',port=27017)
MongoDB = mongoclient['locals']  #连接具体数据库


#
res = MongoDB.users.find({})
print(res)      #<pymongo.cursor.Cursor object at 0x00000213BE3EBAC8>
for i in res:
    print(i.get('_id'),type(i.get('_id')))   #5c3f004a260d3c35a0054ed4 <class 'bson.objectid.ObjectId'>
    i['_id'] = str(i.get('_id'))
    s = json.dumps(i)
    print(s)  #{"_id": "5c3f004a260d3c35a0054ed4",
                # "age": 3.0, "test": 45.0, "id": 2.0, "name": "li-ou"}

res = MongoDB.users.find_one({})#{'_id': ObjectId('5c3f004a260d3c35a0054ed4'), 'age': 3.0, 'test': 45.0, 'id': 2.0, 'name': 'li-ou'}
res = MongoDB.users.find_one({},{'_id':0}) #{'age': 3.0, 'test': 45.0, 'id': 2.0, 'name': 'li-ou'}

#增加
res = MongoDB.users.insert_one({'id':6,'age':44,'test':66,'name':'oup'})
print(res,type(res),res.inserted_id)
#<pymongo.results.InsertOneResult object at 0x000001CBC2C94948>
# <class 'pymongo.results.InsertOneResult'> 5c3f31f46c2a401394c70450

res = MongoDB.users.insert_many([{'id':6,'age':44,'test':66,'name':'oup'},{'id':7,'age':22,'test':56,'name':'hip'}])
print(res,type(res),res.inserted_ids)
#<pymongo.results.InsertManyResult object at 0x0000026F47D74B88>
# <class 'pymongo.results.InsertManyResult'>
# [ObjectId('5c3f32b46c2a403340db44d5'), ObjectId('5c3f32b46c2a403340db44d6')]


#修改
res = MongoDB.users.update_one({'age':44},{'$set':{'name':'liuliu'}})
print(res,dir(res))
#raw_result影响的行数

MongoDB.users.update_many({'age':44},{'$set':{'name':'liuliu'}})

#删除
# MongoDB.users.delete_one({'id':1})
# MongoDB.users.delete_many({'id':1})

#sort  limit  skip

# MongoDB.users.find({}).limit(5).skip(5)
# MongoDB.users.find({}).sort({'age':1})
# MongoDB.users.find({}).sort({'age',pymongo.ASCENDING}) #正序
# MongoDB.users.find({}).sort({'age',pymongo.DESCENDING}) #倒序


#ObjectId模块使用
s = ObjectId('5c3f34536c2a4029b0f83fe4')

res = MongoDB.users.find_one({'id':s})
print(res)

 

posted on 2019-01-16 21:03  诚意  阅读(989)  评论(0编辑  收藏  举报