我是戈兰语和蒙古语的初学者,我使用聚合组 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, },)
2 回答
跃然一笑
TA贡献1826条经验 获得超6个赞
我在mongo内部添加了另一个$project。管道并解决问题。
removeGroupItem := bson.D{
{"$project", bson.D{
{"data.password", 0},
}},
}
result, err := userCollection.Aggregate(ctx,
mongo.Pipeline{
matchStage, groupStage, projectStage, removeGroupItem
},
)
添加回答
举报
0/150
提交
取消