如何删除 golang mongodb 组聚合中的嵌套字段?

How to remove nested field in golang mongodb group aggregation?

我是 golang 和 mongodb 的初学者,我在使用聚合组删除嵌套字段时遇到问题 mongodb。我刚刚阅读了 mongodb 文档,我认为删除字段可以使用 mongodb $project 处理,但我找不到这样做的示例。这是查询的结果

{
    "data": [
        {
            "_id": "60db0920a2f13ba5037c90f5",
            "email": "jodi@admin.com",
            "is_verified": false,
            "password": "...",
            "username": "jodi"
        }
    ],
    "page": 1,
    "per_page": 3,
    "total": 1
}

如何删除密码字段?我应该如何处理此代码?

q := c.Query("q")
perPage, err := strconv.Atoi(c.Query("per_page"))
if err != nil || perPage < 1 {
    perPage = 10
}
page, err := strconv.Atoi(c.Query("page"))
if err != nil || page < 1 {
    page = 1
}
startIndex, err := strconv.Atoi(c.Query("page"))
if err != nil || startIndex < 1 {
    startIndex = 0
} else if startIndex > 0 && page < 1 {
    startIndex = (startIndex * perPage) - perPage
} else {
    startIndex = 0
}
matchStage := bson.D{{"$match", bson.D{{}}}}
if q != "" {
    matchStage = bson.D{
        {"$match", bson.D{
            {"username", q},
        }},
    }
}
groupStage := bson.D{
    {"$group", bson.D{
        {"_id", bson.D{{"_id", "null"}}},
        {"total", bson.D{{"$sum", 1}}},
        {"data", bson.D{{"$push", "$$ROOT"}}},
        {"page", bson.D{{"$first", page}}},
        {"per_page", bson.D{{"$first", perPage}}},
    }}}
projectStage := bson.D{
    {"$project", bson.D{
        {"_id", 0},
        {"total", 1},
        {"page", 1},
        {"per_page", 1},
        {"data", bson.D{{"$slice", []interface{}{"$data", startIndex, perPage}}}},
    }}}
result, err := userCollection.Aggregate(ctx,
    mongo.Pipeline{
        matchStage, groupStage, projectStage,
    },
)

您可以明确指定要在 data 中看到的内部文档中的哪些字段。 Mongo 文档:$project embeded document fields

根据@sirsova 的建议,我在 mongo.Pipline 中添加了另一个 $project 并解决了问题。

removeGroupItem := bson.D{
        {"$project", bson.D{
            {"data.password", 0},
        }},
}
result, err := userCollection.Aggregate(ctx,
    mongo.Pipeline{
        matchStage, groupStage, projectStage, removeGroupItem
    },
)