If you pass a map
as the document to Collection.InsertOne()
, the mongo
package will use the mongo.TransformDocument()
to convert it to a *bson.Document
value, because most operations are only implemented on bson.Document
s.
The current transformation implementation does not handle objectid.ObjectID
nor the time.Time
types. It could and probably should, and I assume it will, but currently it doesn't.
If you want these types to end up with proper types in MongoDB, you may construct and pass a *bson.Document
yourself, in which you can explicitly dictate what the types of the properties should be.
This is an equivalent insert statement to yours, using bson.NewDocument()
to create the document manually:
res, err := coll.InsertOne(context.Background(), bson.NewDocument(
bson.EC.String("string", "test"),
bson.EC.Int64("integer", 123),
bson.EC.Double("float", 0.123),
bson.EC.ArrayFromElements("array",
bson.VC.String("t"), bson.VC.String("e"),
bson.VC.String("s"), bson.VC.String("t")),
bson.EC.ObjectID("objectid", objectid.New()),
bson.EC.DateTime("time", time.Now().UnixNano()/1e6), // Must pass milliseconds
))
It's more verbose, but it's explicit in what we want the result document in MongoDB to be. The result document will look like this:
{
"_id" : ObjectId("5ac5f598ca151255c6fc0ffb"),
"string" : "test",
"integer" : NumberLong(123),
"float" : 0.123,
"array" : [
"t",
"e",
"s",
"t"
],
"objectid" : ObjectId("5ac5f598ca151255c6fc0ffa"),
"time" : ISODate("2018-04-05T10:08:24.148Z")
}
Once the driver improves, I assume your original version will work as expected and produce a document identical to this in structure.