Python操作MongoDB

2018-11-29  本文已影响0人  岑洋

自学整理记录,大神见笑

MongoDB简介

mongoimport -d MongoDB数据库名 -c 集合名 --file json文件路径

python连接mongodb

初始化步骤

from pymongo import MongoClient

client=MongoClient(host="127.0.0.1",port=27017)

collection = client["MyMongo"]["contacts"]

操作数据库

collection.insert_one({"_id":10010,"name":"xiaowang","age":10})

data_list = [{"name":"test1"},{"name":"test2"},{"name":"test3"}]
collection.insert_many(data_list)

[{"name":"test{}".format(i)} for i in range(1000)]

collection.delete_one({"name": "xiaohua"})

collection.delete_many({"name": "xiaohua"})

collection.update_one({"name": "maziao"}, {"$set": {"name": "liuboyang"}})

collection.update_many({"name": "maziao"}, {"$set": {"name": "liuboyang"}})

collection.find_one({"name": "test1"})

result = collection.find({"name": "test1"})
print(list(result))

print(list(result));

2.另外一种是for循环遍历打印每一条

for i in result:
 print(i)

上一篇下一篇

猜你喜欢

热点阅读