1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

mongo-go-driverで「$in」オペレータを使う

Posted at

概要

MongoDBで、複数の値のいずれかに該当するドキュメントを取得する$inオペレーターがあります。今回はmongo-go-driverで $inを使いたい時に、どうすれば良いかを書きます。

対応

How to use the elements of a slice in bson.A using mongo-go-driver 0.2.0の記事にある通り、$inに続く配列の値をbson.A型にして設定します。こちらのドキュメントにある通り、bson.Aはクエリの中で配列を扱う型になります。

実装サンプル

クエリの設定部分のみサンプルとして記載します。コレクション取得までの記載は割愛しますので、詳細は@yotahada-nus3さんのmongoDB公式のGoのDriverを使ってみたの記事をご参考ください。内容としては、絞り込みたい「_id」の内容を保持したsliceを、bson.A型に詰め替えてクエリに設定します。

sample.go
func SampleGetByIDs(ids []string) error {
	// コレクションの取得処理は割愛・・・
	idBsonA := bson.A{}
	for _, id := range ids {
		idBsonA = append(idBsonA, id)
	}
	filter := bson.D{{Key: "_id", Value: bson.D{{Key: "$in", Value: idBsonA}}}}
	cur, err := col.Find(context.Background(), filter)
	// curの取得処理は割愛・・・
}

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?