使用PyMongo操作MongoDB的基本实践(1)——删除,查找,更新

  • 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

参考资料:

mongodb_修改器( inc/ set/ unset/ push/$pop/upsert……)

你可能感兴趣的:(MongoDB)