在mongo中使用aggregate和$unwind之后,如何重新组合列表?

2024-04-18 02:35:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在建立一个总管道如下

pipeline = [ 
        {"$unwind": "$categories"}
    ]
if len(cat_comp) > 0:
        pipeline.append({"$match": {"categories": {"$in": cat_comp}}})

result = mongo.db.xxx.aggregate(pipeline)['result']

问题是,如何在执行聚合时将类别列表重新组合回结果中,因为返回的每个记录都是与列表中的一个项对应的类别字段。如何重建结果,以便对可能列表执行匹配($match),但恢复原始类别列表。你知道吗

有人建议我尝试:

pipeline.append({"$group": {"categories": {"$push": "$categories"}}})

我修改为:

pipeline.append({"$group": {"_id": "anything", "categories": {"$push": "$categories"}}})

然而现在,我只得到一个记录回来,其中有一个类别从所有结果的巨大列表。所以我想做的是,把一个文件看作:

{
"_id": 45666
"categories": ['Fiction', 'Biography']
"other": "sss"
}

并通过传递正则表达式从用户列表category_list = ['Anything', ...]进行搜索,如下所示:

cat_comp = [re.compile(cat, re.IGNORECASE) for cat in cat_list]

最后,aggregate(pipeline)的情况是,由于$unwind,我正在丢失作为列表的“categories”。现在,我如何在输入数据上执行查询,但返回与列表中的category匹配的记录。你知道吗

我也在尝试:

pipeline.append({"$group": {"_id": "$_id", "categories": { "$addToSet": "$categories" } } })

它有效地返回一个列表中包含类别的记录列表-但是,我如何才能看到其余的记录,我只能看到_idcategories。你知道吗


Tags: inid列表pipelinematch记录groupresult