一 ,pymongo模块的下载与使用
pip install pymongo
二,使用
1,连接
import pymongo mongo_client = pymongo.MongoClient(host="127.0.0.1", port=27017) mongo_db = mongo_client["day117"]
2,查
res = mongo_db.user.find() print(res) # <pymongo.cursor.Cursor object at 0x0000028DEAAD03C8> 类似生成器 for data in res: print(data) res = mongo_db.user.find_one({"name": "mmm"}) print(res) print(res.get("_id"))
3,增
# res = mongo_db.chat.insert_one({"sender": "glh", "chat": "今天天气怎么样?", "datatime": time.time()}) # 插入单条 # res = mongo_db.chat.insert_one({"sender": "tuling", "chat": "请问要查询哪所城市?", "datatime": time.time()}) # print(res, res.inserted_id) # res = mongo_db.user.insert_many([{}, {}, {}]) # 插入多条 # print(res, res.inserted_ids)
4,改
res = mongo_db.user.update_one({"name": "mmm"}, {"$set": {"age": 888}}) print(res, res.modified_count) res = mongo_db.user.update_many({"age": {"$gte": 18}}, {"$set": {"age": 789}}) print(res, res.modified_count)
5,删
res = mongo_db.user.delete_one({"$or": [{"name": "lll"}, {"name": "jjj"}]}) print(res, res.deleted_count) res = mongo_db.user.delete_many({}) # 删除所有数据 print(res, res.deleted_count)
原文地址:https://www.cnblogs.com/glh-ty/p/9807272.html
时间: 2024-10-04 03:30:45