爬虫--MongoDB安装及应用
python连接mongodb
#下载包
pip install pymango
from pymongo import MongoClient
#获取客户端
client = MongoClient()
client = MongoClient("mongodb://mongodb0.example.net:27019")
client = MongoClient('localhost', 27017)
#连接数据库
db = client.test
db = clinet['test']
#获取集合
collection = db.col_name
collection = db['col_name']
#插入数据
collection.insert_one(doc)
collection.insert_many(docs)
#查询数据
find(filter=None, projection=None, skip=0, limit=0,
no_cursor_timeout=False, cursor_type=CursorType.NON_TAILABLE,
sort=None, allow_partial_results=False, oplog_replay=False,
modifiers=None, manipulate=True)
find_one(filter_or_id=None, *args, **kwargs)
#遍历查询数据
for doc in collection.find()
print(doc)
#条件查询
from bson import ObjectId
doc = collection.find({'_id':ObjectId('5cb82fab9510257d2ef26f3d')}) #使用_id查询
#更新文档
collection.update_one(filter, update, upsert=False)
collection.update_many(filter, update, upsert=False)
collection.replace_one(filter, replacement, upsert=False)
collection.find_one_and_update(filter, update, projection=None, sort=None, return_document=ReturnDocument.BEFORE, **kwargs)
#删除文档
collection.delete_one(filter)
collection.delete_many(filter)
collection.drop() #删除集合
collection.find_one_and_delete(filter, projection=None, sort=None, **kwargs)
collection.find_one_and_replace(filter, replacement, projection=None, sort=None, return_document=ReturnDocument.BEFORE, **kwargs)
#索引
collection.create_index(keys, **kwargs)
collection.create_indexes(indexes)
collection.drop_index(index_or_name)
collection.drop_indexes()
collection.reindex()
collection.list_indexes()
collection.index_information()