如何删除 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,

    },

)


慕盖茨4494581
浏览 69回答 2
2回答

人到中年有点甜

您可以显式指定要在 内部文档中看到的哪些字段。蒙戈文档:$project嵌入的文档字段data

跃然一笑

我在mongo内部添加了另一个$project。管道并解决问题。removeGroupItem := bson.D{&nbsp; &nbsp; &nbsp; &nbsp; {"$project", bson.D{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {"data.password", 0},&nbsp; &nbsp; &nbsp; &nbsp; }},}result, err := userCollection.Aggregate(ctx,&nbsp; &nbsp; mongo.Pipeline{&nbsp; &nbsp; &nbsp; &nbsp; matchStage, groupStage, projectStage, removeGroupItem&nbsp; &nbsp; },)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java