0

First this is mongodb's data.

{
    _id : 1,
    "Test1" : "Hello",
    "Test2" : "MongoDB!",
}

And this is golang struct.

type P_SET struct {
    _id int
    Test1 string
    Test2 string
}

Next this is my golang code.

var pol P_SET
collection := client.Database("DBName").Collection("CollectionName")
err := collection.FindOne(context.TODO(), bson.M{"_id": 1}).Decode(&pol)

But the result does not come with only _id data.

&{0, "Hello", "MongoDB!"}

I wonder why I can't get only _id values.

SangGeol
  • 65
  • 8
  • 1
    You need to export the _id field, i.e. change it to `ID` or `Id`, and use tags to indicate it should scan the `_id` from mongo. – mkopriva Jan 30 '20 at 07:42
  • ... the rules on decoding are listed here: https://godoc.org/go.mongodb.org/mongo-driver/bson#hdr-Structs – mkopriva Jan 30 '20 at 07:49
  • @mkopriva Oh! This works fine this way. i changed this source code `_id int` => `ID int "_id"`. Thanks!! – SangGeol Jan 30 '20 at 07:50
  • Note that the correct format for tags is `\`bson:"_id"\``, however since you say it works it's possible that the bson decoder already expects the `ID` field so you probably can remove the tag altogether. Here's some example of tags: https://golangcode.com/struct-tags/ – mkopriva Jan 30 '20 at 07:55

0 Answers0