在pymongo遇到的困难在这里记一下(这个版本是3.8)
连接
建立连接
pymongo
conn = pymongo.MongoClient('localhost', 27017)
表
collection = conn['db']['article'] # 或
collection = conn.db.article
表名=连接名['库名']['集合名']
分组
1.group()函数
func = '''
function(obj,prev)
prev.count +=obj.count
'''
ret = collection.group(key=['date'], condition=None, initial={'count': 0}, reduce=func)
print(ret)
按日期给文章分组,并统计浏览量总数count(字典的值是初始值0)
运行结果
[{'date': '2019年08月13日', 'count': 2793.0}, {'date': '2019年06月15日', 'count': 1332.0}, {'date': '2019年07月28日', 'count': 1374.0},...]
2.聚合函数
ret_1 = table.aggregate([{'$group': {"_id": "$date", "count": {"$sum": "$count"}}}])
print(list(ret_1))
结果:
[{'_id': '2019年08月7日', 'count': 93}, {'_id': '2019年08月6日', 'count': 105}, {'_id': '2019年07月7日', 'count': 117},...]
几个常用的参数
- key:分组依据的字段----------------------------参数类型 : list
- condition:是附加条件---------------------------参数类型 : dict
- initial:是想要统计的每组的信息--------------参数类型 : dict
- reduce:函数,书写统计逻辑--------------------参数类型 : str
…
JS代码,该函数的参数 object 是集合中的一条记录,prev是参数initial
排序
升序:pymongo.ASCENDING ( 1 )
降序:pymongo.DESCENDING ( -1 )
ret = collection.find().sort([("date", pymongo.ASCENDING)])
或当做参数传进去
ret = collection.find(sort=[("date", pymongo.ASCENDING)])
查找
-
查询表中所有数据
db.goods.find()
-
等值查询
db.goods.find({“name”:“辣条”})
-
and 与 or
db.goods.find({“name”:“辣条”, “price”:0.5})
db.goods.find({"$or":[{“name”:“辣条”},{“price”:3.5}]}) -
非等值查询:db.goods.find({“定位的键”:{$…:“值”})
greater than ,little than ,equal 大于,小于和相等大于: $gt 和 大于等于: $gte
db.goods.find({"price":{"$gt":0.5}}) db.goods.find({"price":{"$gte":4.5}})
小于: $lt 和 小于等于: $lte
db.goods.find({"price":{"$lt":4.5}}) db.goods.find({"price":{"$lte":4.5}})
不等于: $ne
db.goods.find({"price":{"$ne":5.5}})
上下限范围查询
db.goods.find({"price":{"$lt":5.5, "$gt":0.5}})
非上下限范围查询
db.goods.find({$or:[{"price":{"$lt":3.5}}, {"price":{"$gt":4.5}}]})
更新
table.update({"name":"辣条"},{"$set":{"name":"大辣皮"}})