python中操作MongoDB

pymongo

下载安装pymongo模块

from pymongo import MongoClient

MC = MongoClient("127.0.0.1",27017)
MongoDB = MC["S21DAY93"]# 要用的数据库名称,如果没有存入数据时,直接创建

具体用法

操作数据库和终端操作MongoDB基本一样,细微的差别是方法名构造,终端中是类似驼峰型,如:findOne,而在python中使用下划线连接,find_one,
只有在一个位置有很大不同,高级函数sort的用法

终端操作中:

db.users.find({}).sort({age:-1}) 依照age字段进行倒序
db.users.find({}).sort({age:1}) 依照age字段进行正序

python中:

from pymongo import DESCENDING,ASCENDING
res = MongoDB.Users.find({}).sort("age",ASCENDING)
for row in res:
    print(row)

python中使用MongoDB

from pymongo import MongoClient
from bson import ObjectId

MC = MongoClient("127.0.0.1",27017)
MongoDB = MC["S21DAY93"]

# res = MongoDB.Users.insert_one({"name":"YWB","age":999})
# res = MongoDB.Users.insert_many([{"name":"JWB","age":999},{"name":"wpq","age":999}])
# print(res.inserted_id,type(res.inserted_id))
# print(res.inserted_ids,type(res.inserted_ids))

# res = MongoDB.Users.find({"_id":ObjectId("5d50e778b2a72712f5ee54c5")})
# res = MongoDB.Users.find_one({"name":"YWB"})
# <pymongo.cursor.Cursor object at 0x000001F6C5027550> 生成器
# for row in res :
#     print(row)
# print(res)


# 改:
# MongoDB.Users.update_one({},{"$inc":{"age":1}})
# MongoDB.Users.update_many({"age":1000},{"$inc":{"age":1}})

# 删除数据
# MongoDB.Users.delete_one({})
# MongoDB.Users.delete_many({})



# 高级函数
# from pymongo import DESCENDING,ASCENDING
# res = MongoDB.Users.find({}).sort("age",ASCENDING)
# for row in res:
#     print(row)

相关推荐