我試圖在 MongoDB 中找到我的用戶,但是當我運行這段代碼時:type Person struct { Id bson.ObjectId `bson:"_id,omitempty"`//`json:"id" bson:"_id,omitempty"` username string `json:"username" bson:"username"` score string `json:"score" bson:"score"` level string `json:"level" bson:"level"`}result := Person{}var id = "5b8a45912ed6f24d945bee38"err = c.Find(bson.M{"_id":bson.ObjectIdHex(id)}).Select(bson.M{"username": 1, "score":1, "level": 1}).One(&result)fmt.Println(result)只是它告訴我:{ObjectIdHex("5b8a45912ed6f24d945bee38") }并且不返回其他值!非常感謝您的參與!
2 回答

慕蓋茨4494581
TA貢獻1850條經驗 獲得超11個贊
您必須導出所有受封送處理/解封處理的結構字段,因此將它們的名稱更改為以大寫字母開頭:
type Person struct {
? ? Id? ? ? ?bson.ObjectId `bson:"_id,omitempty"`//`json:"id" bson:"_id,omitempty"`
? ? Username string? ? ? ? `json:"username" bson:"username"`
? ? Score? ? string? ? ? ? `json:"score" bson:"score"`
? ? Level? ? string? ? ? ? `json:"level" bson:"level"`
}
另請注意,要按 ID 查找文檔,您可以使用Collection.FindId()
:
err = c.FindId(bson.ObjectIdHex(id)).
? ? Select(bson.M{"username": 1, "score":1, "level": 1}).One(&result)

白板的微信
TA貢獻1883條經驗 獲得超3個贊
只是你應該在結構名稱的第一個中使用大寫字母!而且你也不需要
Select(bson.M{"username": 1, "score":1, "level": 1})
你可以寫 :
err = c.FindId(bson.ObjectIdHex(id)).One(&result)
祝你好運 :))
- 2 回答
- 0 關注
- 112 瀏覽
添加回答
舉報
0/150
提交
取消