LoginSignup
0
1

More than 3 years have passed since last update.

mongo-go-driverでクエリを書く時「primitive.E composite literal uses unkeyed fields」のwarningが表示される

Posted at

概要

GolangでMongoDBを使うとなった時に、おそらく使用するのがmongo-go-driverでしょう。mongo-go-driverではこちらのサンプルにある通り、bsonDという型にクエリの項目を入れていくのですが、この通りに設定していくとprimitive.E composite literal uses unkeyed fieldsというワーニングが表示されます。
ワーニングなので、このままにしておいても良いのですが、ワーニングを消すためにどうすれば良いのかというのを今回書きます。

対応

MongoDBの Offical Go言語 Driverを使ってみる(1)準備・Insertの記事によると、bsonDprimitive.Eのスライスとして定義されているので、きちんと型を書かないとワーニングが出るみたいです。ちなみに、primitive.EとはドキュメントによるとKeyとValueが定義されている構造体です。
対応としてはComposite literal uses unkeyed fieldsの記事に色々と対応が記載されています。ワーニングを出ない設定にするものや、愚直にprimitive.Eの型で書いていくものなどが挙げられています。ちなみに、primitive.Eの記述は省略できるみたいなので、以下の実装サンプルのように書くのが、個人的に良いかなと感じました。

実装サンプル

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)
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1