安装pymongo库
pip install pymongo
操作
# coding=utf-8 from pymongo import MongoClient # 实例化 client = MongoClient(host="127.0.0.1",port=27017) collection = client["test1"]["t1"] # 连接数据库 数据表 # 查询所有 返回Cursor集合 ret = collection.find() # ret = list(ret) # 插入一条数据 返回objectId collection.insert({"name":"zhangsan","age":19}) # 插入多条数据 返回一个列表 item_list = [{"name":"item{}".format(i)} for i in range(1000)] ret = collection.insert_many(item_list) print(ret.inserted_ids) # 修改一条数据 ret = collection.update_one({"name":"item5"},{"$set":{"name":"new-item5"}}) print(ret) # 修改全部数据 ret = collection.update_many({"name":"item2"},{"$set":{"name":"new-item2"}}) print(ret) # 删除一条数据 ret = collection.delete_one({"name":"item3"}) print(ret) # 删除多条数据 ret = collection.delete_many({"name":"item3"}) print(ret) # 查找一条数据 ret = collection.find_one({"name":"item2"}) # 查找多条数据 ret = collection.find({"name":"item3"}) for i in ret: print(i)
原文:https://www.cnblogs.com/yifengs/p/11778383.html