最近写爬虫用到的是mongodb数据库,部署在阿里云的服务器,下面简单记录一下用到的操作,已被后用。(关于mongodb的安装配置参考其他资料,后续补充)
基本操作:
def find_data():
print("init mongo")
client = MongoClient(ip)
db = client[database]
db.authenticate(user, pwd)
c = db[collection]
# c.create_index("movieid", unique=True)
# 其余操作
client.close()
插入:
可以使用insert_one或者insert_many插入多条数据,但是我插入的数据经常会有重复,因此想到两种解决方法。
以豆瓣电影的一条记录来说:

首先建立唯一索引:
c.create_index("movieid", unique=True)
- 利用
try catch
来保证唯一插入,try catch
也可用于其他异常处理
try:
insert_one #说明有相同记录
except e:
print(e)
- upsert命令:
collection.update_one({"movieid": movieid}, {"$set": item}, upsert=True)
上述用于更新一条记录,不存在则插入。{"$set": item}
, 全部更新,也可选择部分更新。
查找find操作
-
results = c.find().count()
用于记录,find中可以加条件。
mark = "wish_count"
results = c.find({"subtype": "tv", mark: {"$gte": 10000, "$lte": 30000}}, {"_id": 0, "title": 1, "rate": 1, mark: 1}).sort([("rate", -1), (mark, -1)])
这条语句的意思是;根据subtype=“tv”
, mark
在10000~30000
之间进行查找,结果中不显示_id
字段(find的第二个参数,0不显示,1显示), 显示title
和rate
字段。
结果按照rate, mark的顺序降序排列(1为升序)。
-
results = c.find({"title": {"$regex": "大明"}})
类似like操作,查找title包含大明的集合。 -
results = c.find({"casts": {"$in": ["1", "2"]}})
查找集合中演员列表存在1, 2字段的集合。
组合操作:
pipeline = [
{"$match": {"subtype": "tv"}},
{"$unwind": "$casts"},
{"$group": {"_id": "$casts", "count": {"$sum": 1}, "avg": {"$avg": "$rate"}}},
{"$sort": {"avg": -1}},
# {"$match": {"count": {"$gte": 3, "$lte": 4}}}
{"$match": {"_id": "鹿晗"}}
]
results = c.aggregate(pipeline)
组合操作:
第一个match
和find
的第一个参数一样,用于组合前筛选。
unwind
:展开,用于该字段是列表时,展开进行组合操作,不是列表可省略。
group
:_id
是必须字段,count
, avg
自定义字段, sum
, avg
分别是求和,求平均操作。
sort
关键字不在叙述。
后面match
用于组合后筛选, gte
是大于等于,lte
是小于等于字段。
综上:这条操作的意思是:
对subtype=“tv”
的集合进行操作,展开casts
字段,对其进行组合,计算出现次数count
, 对集合的rate
求平均值。结果按照平均值排序,并筛选出count在3~4之间
的集合(_id=“鹿晗”)
。
后续用到再补充,具体其他操作请查看官方文档。
网友评论