【问题标题】:Exclude _id field during a join query在连接查询期间排除 _id 字段
【发布时间】:2022-01-15 07:36:03
【问题描述】:

我尝试创建一个连接查询并从我的结果中排除 _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 参数添加到我的查询的语法是什么。

【问题讨论】:

  • 在最后添加一个$project阶段如何通过_id: false排除_id字段?

标签: python mongodb pymongo


【解决方案1】:

您应该能够在管道中使用 MongoDB $project 来仅选择您想要返回的那些字段。在这种特殊情况下,您可以排除 _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"] }

您可以在 Stackoverflow 上的 this very similar question 中阅读更多相关信息。 我希望这行得通!

【讨论】:

  • 谢谢!效果很好!
猜你喜欢
  • 2018-07-22
  • 1970-01-01
  • 2013-02-18
  • 1970-01-01
  • 2018-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多