When it comes to using MongoDB with Golang, you probably use mongo-go-driver. In mongo-go-driver, as shown in the sample of here, the query item is put in the type bsonD
. As you set it, the warning primitive.E composite literal uses unkeyed fields
will be displayed.
Since it is a warning, you can leave it as it is, but this time I will write about what to do to eliminate the warning.
According to the article Try using MongoDB's Offical Go language driver (1) Preparation / Insert, bsonD
is defined as a slice of primitive.E
, so you have to write the type properly. There seems to be a warning. By the way, primitive.E is a structure in which Key and Value are defined according to Document.
As for the correspondence, various correspondences are described in the article of Composite literal uses unkeyed fields. Some are set so that no warning is issued, and some are written in the primitive.E type in a straightforward manner. By the way, it seems that the description of primitive.E
can be omitted, so I personally felt that it would be better to write it like the implementation sample below.
sample.go
findOptions := options.Find()
findOptions.SetSort(bson.D{{Key: "date", Value: 1}})
filter := bson.D{{Key: "status", Value: "on"},
{Key: "date", Value: bson.D{{Key: "$lt", Value: time.Now()}}}}
cur, err := col.Find(context.Background(), filter, findOptions)