使用PyMongo操作MongoDB的基本實踐(1)——刪除,查詢,更新
阿新 • • 發佈:2018-12-24
db.drop_collection("collection_name")
刪除整個collection
import pymongo
client = pymongo.MongoClient('localhost', 27017)
TempleSpider = client['TempleSpider']
TempleSpider.drop_collection('temple_detail')
collection.delete_one()
刪除指定的doc
for temple in temple_detail.find():
if '牛街' in temple['temple_name' ] or not temple['temple_name'].endswith('寺'):
temple_detail.delete_one({'temple_name': temple['temple_name']})
collection.find_one()
找到指定的doc
print(temple_detail.find_one({'temple_name': '潭柘寺'}))
$set
用來指定一個鍵並更新鍵值,若鍵不存在並建立
temple_detail.update({'temple_name': '潭柘寺'}, {"$set": {"TEL" : "666666", "Password": "123"}})
- 使用修改器
$unset
時,不論對目標鍵使用1、0、-1或者具體的字串等都是可以刪除該目標鍵
temple_detail.update({'temple_name': '潭柘寺'}, {"$unset": {"TEL": "", "Password": ""}})
import pymongo
client = pymongo.MongoClient('localhost', 27017)
TempleSpider = client['TempleSpider']
#TempleSpider.drop_collection('temple_detail')
temple_detail = TempleSpider['temple_detail']
for temple in temple_detail.find():
if '牛街' in temple['temple_name'] or not temple['temple_name'].endswith('寺'):
temple_detail.delete_one({'temple_name': temple['temple_name']})
print(temple_detail.find_one({'temple_name': '潭柘寺'}))
# $set用來指定一個鍵並更新鍵值,若鍵不存在並建立。
temple_detail.update({'temple_name': '潭柘寺'}, {"$set": {"TEL": "666666", "Password": "123"}})
print(temple_detail.find_one({'temple_name': '潭柘寺'}))
# 使用修改器$unset時,不論對目標鍵使用1、0、-1或者具體的字串等都是可以刪除該目標鍵。
temple_detail.update({'temple_name': '潭柘寺'}, {"$unset": {"TEL": "", "Password": ""}})
print(temple_detail.find_one({'temple_name': '潭柘寺'}))
{'temple_url': 'http://www.mafengwo.cn/poi/6910.html', '_id': ObjectId('58e51dc4a30ab01fe847ba23'), 'temple_name': '潭柘寺'}
{'TEL': '666666', 'Password': '123', 'temple_url': 'http://www.mafengwo.cn/poi/6910.html', '_id': ObjectId('58e51dc4a30ab01fe847ba23'), 'temple_name': '潭柘寺'}
{'temple_url': 'http://www.mafengwo.cn/poi/6910.html', '_id': ObjectId('58e51dc4a30ab01fe847ba23'), 'temple_name': '潭柘寺'}
Process finished with exit code 0
參考資料: