MongoDB使用方法
检索类
- 指定列表字段存在并且不等于空列表
{$and: [{ 'xxxfield1': {$exists: true, $type: "array", $ne: []} } ]}
- 指定列表字段存在并且不等于指定值
{"$and" : {"xxxfield1": {$exists: True, $type: "array", $ne: [] }}, {"xxxfield1": {$ne: "xxxvalue1"}} ] }
聚合类
pipeline = []
dict_match = {"xxxfield1": "xxxvalue1"}
if dict_match:
pipeline = [{"$match": dict_match}]
# pipeline.append( {"$unwind": "${0}".format("xxxfield1")} ) # 列表嵌套拆分,如果该字段有下级嵌套,则需要
dict_agg = {"$group": {"_id": "${0}".format("xxxfield1"), "count": {"$sum": 1}}} # 指定聚合内容
dict_sort = {"$sort": SON([("count", 1), ("_id", 1)])} # 指定排序
dict_limit = {"$limit": 10} # 指定返回聚合结果返回数据条数, 比如10
pipeline.extend( [dict_agg, dict_sort, dict_limit] ) # 聚合函数参数拼接
res = db["tablename"].aggregate(pipeline)
for ele_dict in res:
print (ele_dict)