摘要:使用 PyMongo 模块连接 MongoDB 数据库,并进行常规增删改查操作。
操作数据库
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import pymongo
client = pymongo.MongoClient("localhost",27017)
db_test = client["test"]
collection_used = db_test["demo"]
x = collection_used.find() for i in x: print(i) print(i["name"]) print(type(i)) break
|
新增文档
语法:
collection.insert_one( {doc} )
collection.insert_one([ {doc1},{doc2},{doc3} ])
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import pymongo
client = pymongo.MongoClient("localhost", 27017)
db_used = client["test"]
collection_used = db_used["demo"]
collection_used.insert_one({"name": "legalgeek-8", "age": 25})
collection_used.insert_many([{"name": "legalgeek-9", "age": 27}, {"name": "IU", "age": 30}])
|
查找文档
语法:
collection.find_one( )
collection.find( )
collection.find( {条件} )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| import pymongo
client = pymongo.MongoClient("localhost", 27017)
db_used = client["test"]
collection_used = db_used["demo"]
x = collection_used.find_one() print(x)
y = collection_used.find() for i in y: print(i)
z = collection_used.find({"name":"legalgeek"}) for i in z: print(i)
|
更新文档
语法:
collection.update_one( {“key”:“value”}, {"$set":{"修改目标字段":""}} )
collection.update_many({“key”:“value”}, {"$set":{"修改目标字段":""}} )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import pymongo
client = pymongo.MongoClient("localhost", 27017)
db_used = client["test"]
collection_used = db_used["demo"]
collection_used.update_one({"name":"legalgeek-1"},{"$set":{"age":88}})
collection_used.update_many({"name":"legalgeek"},{"$set":{"age":77}})
|
删除文档
语法:
collection.delete_one({条件})
collection.delete_many({条件})
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import pymongo
client = pymongo.MongoClient("localhost", 27017)
db_used = client["test"]
collection_used = db_used["demo"]
collection_used.delete_one({"name":"legalgeek-2"})
collection_used.delete_many({"name":"legalgeek"})
|