备忘录:
练习,即可。
1.增删改查
import pymongo
class MongoUtils:
def __init__(self,host, port,dbName):
self.client = pymongo.MongoClient(host=host, port=port)
self.db = self.client[dbName]
def getDb(self):
return self.db
def getCollection(self,collectName):
return self.db[collectName]
def main():
print("测试MongoDB")
host = "localhost"
port = 27017
dbName = "demo01"
utils = MongoUtils(host,port,dbName)
#插入一条数据
print("插入一条数据:")
info01 = {"GIRL_ID": "2020032901", "GIRL_NAME": "Yao", "AGE": 31, "HEIGHT": "162", "CUP_SIZE": "B"}
result01 = utils.getCollection("girlInfo01").insert_one(info01)
print(result01)
#插入多条数据
print("插入多条数据:")
info02 = {"GIRL_ID": "2020032902", "GIRL_NAME": "Hong", "AGE": 29, "HEIGHT": "163", "CUP_SIZE": "A"}
info03 = {"GIRL_ID": "2020032903", "GIRL_NAME": "Yuan", "AGE": 30, "HEIGHT": "160", "CUP_SIZE": "C"}
info04 = {"GIRL_ID": "2020032904", "GIRL_NAME": "Zhang", "AGE": 25, "HEIGHT": "161", "CUP_SIZE": "D"}
result02 = utils.getCollection("girlInfo01").insert_many([info02,info03,info04])
print(result02)
#查找多条数据
print("条件查询,查找多条数据:")
results = utils.getCollection("girlInfo01").find()
print(type(results))
for result in results:
print(result)
# 查找一条数据
print("条件查询,查找一条数据:")
result = utils.getCollection("girlInfo01").find_one({"GIRL_ID": "2020032903"})
print(result)
#条件查询 大于26
print("条件查询,大于26:")
results = utils.getCollection("girlInfo01").find({"AGE": {'$gt': 26}})
for result in results:
print(result)
#更新
print("更新:")
results = utils.getCollection("girlInfo01").update({"GIRL_ID":"2020032904"},{"$set":{"CUP_SIZE": "E"}})
result = utils.getCollection("girlInfo01").find_one({"GIRL_ID": "2020032904"})
print(result)
#删除
print("删除:")
result = utils.getCollection("girlInfo01").remove({"GIRL_ID": "2020032904"})
print(result)
if __name__ == '__main__':
main()
2.数据格式
{"GIRL_ID":"2020032901","GIRL_NAME":"Yao","AGE":31 ,"HEIGHT":"162" ,"CUP_SIZE":"B"}
{"GIRL_ID":"2020032902","GIRL_NAME":"Hong","AGE":29 ,"HEIGHT":"163" ,"CUP_SIZE":"A"}
{"GIRL_ID":"2020032903","GIRL_NAME":"Yuan","AGE":30 ,"HEIGHT":"160" ,"CUP_SIZE":"C"}
{"GIRL_ID":"2020032904","GIRL_NAME":"Zhang","AGE":25 ,"HEIGHT":"161" ,"CUP_SIZE":"D"}
3.安装模块指令
pip3 install pymongo
以上,感谢。