@Lars_Krieger to answer your specific question:
MongoDB supports many different types in the _id
field (e.g. ObjectID
, string
, int
, etc; see Field Names for more information), so the Go driver has to return the _id
as an interface{}
because it won’t always be an ObjectID
.
For example, if you use a string
for _id
, you get back a string
:
res, _ := coll.InsertOne(context.Background(), bson.D{{"_id", "abcd"}, {"key", "value"}})
fmt.Printf("%v, type = %T\n", res.InsertedID, res.InsertedID)
// abcd, type = string
If you use an int
for _id
, you get back an int32
:
res, _ := coll.InsertOne(context.Background(), bson.D{{"_id", 1234}, {"key", "value"}})
fmt.Printf("%v, type = %T\n", res.InsertedID, res.InsertedID)
// 1234, type = int32
If you don’t specify an _id
, the driver automatically generates an ObjectID
:
res, _ := coll.InsertOne(context.Background(), bson.D{{"key", "value"}})
fmt.Printf("%v, type = %T\n", res.InsertedID, res.InsertedID)
// ObjectID(61895f6da6881b5cfc508e65), type = primitive.ObjectID