Overview
このガイドでは、単一のコレクション全体で指定されたフィールドの個別の値を取得する方法を学習できます。
サンプル データ
このガイドの例では、courses
コレクション内のドキュメントのモデルとして次の Course
構造体を使用しています。
type Course struct { Title string Department string Enrollment int32 }
例えを実行するには、次のスニペットを使用してサンプルデータをdb.courses
コレクションにロードします。
coll := client.Database("db").Collection("courses") docs := []interface{}{ Course{Title: "World Fiction", Department: "English", Enrollment: 35}, Course{Title: "Abstract Algebra", Department: "Mathematics", Enrollment: 60}, Course{Title: "Modern Poetry", Department: "English", Enrollment: 12}, Course{Title: "Plate Tectonics", Department: "Geology", Enrollment: 30}, } result, err := coll.InsertMany(context.TODO(), docs)
Tip
存在しないデータベースとコレクション
書き込み操作を実行するときに必要なデータベースとコレクションが存在しない場合は、サーバーが暗黙的にそれらを作成します。
各ドキュメントには、コース名、部門、登録者数を含む大学コースの説明が含まれています。 これらの項目は、各ドキュメントのtitle
、 department
、 enrollment
フィールドに対応します。
distinct
単一のコレクション全体で指定されたフィールドの個別の値を検索するには、次のパラメータをDistinct()
メソッドに渡します。
個別の値を取得するフィールド名
一致するドキュメントを指定する
non-nil
クエリフィルター
Tip
空のクエリフィルターを指定すると、 Distinct()
メソッドはコレクション内のすべてのドキュメントにわたって個別の値を検索します。
動作の変更
DistinctOptions
を渡すことで、 Distinct()
メソッドの動作を変更できます。 DistinctOptions
を指定しない場合、ドライバーは各オプションのデフォルト値を使用します。
DistinctOptions
タイプでは、次の方法でオプションを設定できます。
方式 | 説明 |
---|---|
| The type of language collation to use when sorting results. Default: nil |
| Sets a comment to attach to the distinct operation. Default: nil |
例
次の例では、 enrollment
フィールドの値が 50
より小さいドキュメントを検索し、Distinct()
メソッドを使用して department
フィールドの個別の値を出力します。
filter := bson.D{{"enrollment", bson.D{{"$lt", 50}}}} var arr []string err = coll.Distinct(context.TODO(), "department", filter).Decode(&arr) if err != nil { panic(err) } fmt.Printf("%s\n", arr)
[English Geology]
個別の値の取得の例: 完全なファイル
注意
セットアップ例
この例では、接続 URI を使用してMongoDBのインスタンスに接続します。MongoDBインスタンスへの接続の詳細については、「 MongoClient の作成ガイド 」を参照してください。この例では、 Atlasサンプルデータセット に含まれる sample_restaurants
データベースの restaurants
コレクションも使用します。「Atlas を使い始める」ガイドに従って、 MongoDB Atlasの無料階層のデータベースにロードできます。
この例では、 restaurant
コレクションに対して次のアクションを実行しています。
cuisine
フィールドの値が"Tapas"
であるドキュメントに一致します一致したドキュメントから
borough
フィールドの個別の値を返します
// Retrieves distinct values of a field by using the Go driver package main import ( "context" "fmt" "log" "os" "github.com/joho/godotenv" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options" ) type Restaurant struct { ID bson.ObjectID `bson:"_id"` Name string RestaurantId string `bson:"restaurant_id"` Cuisine string Address interface{} Borough string Grades interface{} } func main() { if err := godotenv.Load(); err != nil { log.Println("No .env file found") } var uri string if uri = os.Getenv("MONGODB_URI"); uri == "" { log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/ja-jp/docs/drivers/go/current/usage-examples/#environment-variable") } client, err := mongo.Connect(options.Client().ApplyURI(uri)) if err != nil { panic(err) } defer func() { if err = client.Disconnect(context.TODO()); err != nil { panic(err) } }() // Filters the collection for documents where the value of cuisine is "Tapas" coll := client.Database("sample_restaurants").Collection("restaurants") filter := bson.D{{"cuisine", "Tapas"}} // Retrieves the distinct values of the "borough" field in documents // that match the filter var arr []string err = coll.Distinct(context.TODO(), "borough", filter).Decode(&arr) if err != nil { panic(err) } // Prints the distinct "borough" values for _, result := range arr { fmt.Println(result) } // When you run this file, it should print: // Brooklyn // Manhattan // Queens }
Brooklyn Manhattan Queens
詳細情報
クエリフィルターの作成の詳細については、「クエリの指定 」を参照してください。
API ドキュメント
このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。