使用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……)

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值