Search code examples
mongodbgogo-gin

How to remove nested field in golang mongodb group aggregation?


I beginner in golang and mongodb, and I have problem with remove nested field using aggregate group mongodb. I just read the mongodb doc and I think remove field can handle with mongodb $project but I cant find the example to do that. this is the result of query

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

how to remove password field? what should I do with this code?

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,
    },
)

Solution

  • based on @sirsova suggestion, I add another $project inside mongo.Pipline and solve the problem.

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