@Stennie: Thanks for the detailed explanations. I had seen the mentioned examples already, but they are looking very low level and not Go idiomatic for me. So I came up to this:
// Size defines the item size
type Size struct {
H int
W float64
Uom string
}
// Item defines an item
type Item struct {
OID objectid.ObjectID `bson:"_id,omitempty"` // omitempty not working
Item string
Qty int
Tags []string
Size Size
}
func main() {
// connect to MongoDB
client, err := mongo.Connect(context.Background(), "mongodb://localhost:27017", nil)
if err != nil {
log.Fatal(err)
}
db := client.Database("mongosample")
inventory := db.Collection("inventory")
// write document
itemWrite := Item{Item: "canvas", Qty: 100, Tags: []string{"cotton"}, Size: Size{H: 28, W: 35.5, Uom: "cm"}}
itemWrite.OID = objectid.New()
fmt.Printf("itemWrite = %v\n", itemWrite)
result, err := inventory.InsertOne(context.Background(), itemWrite)
if err != nil {
log.Fatal(err)
}
fmt.Printf("result = %#v\n", result)
// read documents
cursor, err := inventory.Find(
context.Background(),
bson.NewDocument(bson.EC.String("item", "canvas")),
)
if err != nil {
log.Fatal(err)
}
defer cursor.Close(context.Background())
itemRead := Item{}
for cursor.Next(context.Background()) {
err := cursor.Decode(&itemRead)
if err != nil {
log.Fatal(err)
}
fmt.Printf("itemRead = %v\n", itemRead)
}
}
I have no need to control the ObjectID in the application and want to let the driver or database generate the ID on demand. Problem here: I couldn't find a way to omit the ID. This bson:"_id,omitempty"
isn't working. It leeds to an OID with everything set to zero 'ObjectID("000000000000000000000000")'. Maybe a general problem because ObjectID is an array and not a slice: type ObjectID [12]byte