0

I try to find my user in MongoDB but when I run this code :

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)

Just It show me :

{ObjectIdHex("5b8a45912ed6f24d945bee38") }

And don't return other value!

Thank you so much for your time!

icza
  • 389,944
  • 63
  • 907
  • 827

2 Answers2

4

You have to export all struct fields subject to marshaling / unmarshaling, so change their name to start with capital letter:

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"`
}

Also note that to find a document by its ID, you may use Collection.FindId():

err = c.FindId(bson.ObjectIdHex(id)).
    Select(bson.M{"username": 1, "score":1, "level": 1}).One(&result)
icza
  • 389,944
  • 63
  • 907
  • 827
0

Just you should use the capital letter in first of struct names! And also you don't need

 Select(bson.M{"username": 1, "score":1, "level": 1})

You can write :

err = c.FindId(bson.ObjectIdHex(id)).One(&result)

Good Luck :))