在连接查询期间排除 _id 字段

Exclude _id field during a join query

我尝试创建一个连接查询并从我的结果中排除 _id 字段

    stage_lookup_comments = {
        "$lookup": {
                "from": "products",
                "localField": "product_codename",
                "foreignField": "codename",
                "as": "product",
        }

    }

    pipeline = [
        { "$match": {
            "category":category,
            "archived_at":{"$eq": None}
            }
        },
        stage_lookup_comments
        ]

    array = await db[collection].aggregate(pipeline).to_list(CURSOR_LIMIT)
    return array

我不知道将 "_id": 0 参数添加到我的查询的语法是什么。

您应该能够在您的管道中使用 MongoDB $project 到 select 只有那些您想要 return 的字段。在这种特殊情况下,您可以排除 _id 字段,因为您已经提到将 _id:0.

阅读有关 $project here 的文档以获取更多详细信息。

我没有测试它,但您的查询应该类似于以下内容:

stage_lookup_comments = {
        "$lookup": {
                "from": "products",
                "localField": "product_codename",
                "foreignField": "codename",
                "as": "product",
        }

    }

    pipeline = [
        { 
          "$match": {
             "category":category,
             "archived_at":{"$eq": None}
           }
        },
        stage_lookup_comments,
        { 
           $project: { "_id": 0 } 
        }

    ]

    array = await db[collection].aggregate(pipeline).to_list(CURSOR_LIMIT)
    return array


编辑:

此外,从 MongoDB 4.2 开始,您可以使用运算符 $unset 明确地从文档中删除字段(参见文档 here):

{ $unset: ["_id"] }

您可以在 Whosebug 上的 this very similar question 中阅读更多相关信息。 我希望这有效!