安装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)
使用列表推导式
# coding=utf-8 from pymongo import MongoClient client = MongoClient() coll = client["test1"]["t34"] # 向t34插入1000条数据,_id为0,1,2 name为py0,py1,py2... item_list = [{"_id":i,"name":"py{}".format(i)} for i in range(1000)] print(item_list) ret = coll.insert_many(item_list) # 读取_id为整百的数据 ret = coll.find() # 读取所有数据 ret = list(ret) # 讲数据列表化 data = [i for i in ret if i["_id"]%100==0 and i["_id"]!=0] print(data)