Search code examples
mongodbgobsonmongo-go

Necessity of bson struct tag when using with MongoDB go client


I am watching a tutorial on how to create Go restful APIs that use MongoDB for persistence (this one to be more precise).

The instructor is using in his model (struct) both json and bson tags, something like

type NoteUpdate struct {
    ID        string `json:"id,omitempty" bson:"_id,omitempty"`
    Title     string `json:"title" bson:"title,omitempty"`
    Content   string `json:"content" bson:"content,omitempty"`
    ChangedAt int64  `json:"changed_at" bson:"changed_at"`
}

However the official go driver example does not do so.

As a matter of fact there, no struct tags are used at all.

What is the purpose / usefulness of using bson tags?

The one thing that comes to my mind is the case were one would want to create custom mongo _id fields in which case an explicit bson mapping with that struct's field should be declared.

Is there any other added value for the bson tags?


Solution

  • The MongoDB drivers use only the bson tags. json tags are solely for the encoding/json package (or other 3rd party packages dealing with JSON marshaling/unmarshaling).

    You are not required to specify and use bson tags, in which case the drivers usually just use the lowercased field names when encoding struct values. bson tags are required however when you need a different name.

    And it's also a good practice to specify bson tags even if you want to use the lowercased field names, because there might come a time when you need to rename struct fields, and that would cause troubles and inconsistencies. If you specify bson tags, it won't matter if you rename fields in the future, they will be still marshalled into the same properties, and unmarshaling them will continue to work.