LoginSignup
0
0

More than 1 year has passed since last update.

MongoDBのfindで配列フィールドの登録数を不等号条件でfilterしたい

Posted at

概要

MongoDBではフィールドに配列の型を持てますが、その登録数をfindで条件にしたい時もあるかなと思います。
特定の数(例えば配列の中に1個登録)を条件にしたい場合は、$sizeのオペレーターを使用すれば大丈夫ですが、1個以上とか不等号を使いたくなる場合もありますよね。ただ、$sizeは数値型しか設定できないので、例えばarray_field : { $size: { $gt : 1 }のような指定は不可となります。
では、このように不等号を使いたい場合は、どのように対応すれば良いのかというのをメモ書きします。

対応方法

Is there a way to query array fields with size greater than some specified value?にいくつか対応方法が挙げられてます。一番短く書けそうなのが{ “countries.1” : { “$exists” : true } }のような感じで、配列のフィールドに条件を指定したい項番を指定して$existsを指定します。

実装サンプル

Golangで実装した場合のサンプルを、以下に記します。以下のサンプルでは、array_fileldの配列に一つ以上の項目が登録されているドキュメントを取得します。

sample.go
// コレクション取得までの接続処理は割愛・・
// filter条件の設定
filter := bson.D{{Key: "array_fileld.0", Value: bson.D{
  {Key: "$exists", Value: true}},
}}
// クエリ発行
cur, err := col.Find(context.Background(), filter)
// カーソルからの取得処理は割愛・・
0
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
0
0