Struct ID as string and without tags

In all the examples I find about mapping golang structs to mongodb, the ID field is defined as type primitive.ObjectID and the bson filters tag is also used.

Question:

Must the ID field be of type primitive.ObjectID? I prefer to use string.
I read somewhere that field tags are not mandatory, but in that case, how will the driver know that the ID field of my struct is the same as the _id field of the bank?

Hey @Matheus_Saraiva thanks for the question! According to the Document page in the MongoDB manual:

The _id field may contain values of any BSON data type, other than an array, regex, or undefined.

So yes, you should be able to use a string as a document _id field. As far as field tags, they aren’t mandatory if you’re OK with the default BSON document field name based on the Go struct field name. However, there’s no Go struct field name that automatically maps to BSON document field name _id, so you would need to specify a struct tag if you want to explicitly specify the document _id.

For example, consider the following code without struct tags:

type myDocument1 struct {
	ID   string
	Name string
}

func main() {
	b, _ := bson.Marshal(myDocument1{ID: "abcd", Name: "Bob"})
	fmt.Println(bson.Raw(b))
}

That code prints:

{"id": "abcd","name": "Bob"}

Then consider the following code using a struct tag:

type myDocument2 struct {
	ID   string `bson:"_id"`
	Name string
}

func main() {
	b, _ := bson.Marshal(myDocument2{ID: "abcd", Name: "Bob"})
	fmt.Println(bson.Raw(b))
}

That code prints:

{"_id": "abcd","name": "Bob"}

Check out a working example of both here.

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.