Overview
このガイドでは、単一のコレクション全体で指定されたフィールドの個別の値を取得する方法を学習できます。
サンプル データ
このガイドの例えでは、courses コレクション内のドキュメントのモデルとして次の Course 構造体を使用しています。
type Course struct { Title string Department string Enrollment int32}例えを実行するには、次のスニペットを使用してサンプルデータをdb.coursesコレクションにロードします。
coll := client.Database("db").Collection("courses")docs := []any{ 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 タイプでは、次の方法でオプションを設定できます。
方式 | 説明 |
|---|---|
| 結果をソートするときに使用する言語照合のタイプ。 |
| 個別の操作に接続するコメントを設定します。 |
例
次の例では、 enrollmentフィールドの値が 50 より小さいドキュメントを検索し、Distinct() メソッドを使用して departmentフィールドの個別の値を出力します。
filter := bson.D{{"enrollment", bson.D{{"$lt", 50}}}}
var arr []stringerr = coll.Distinct(context.TODO(), "department", filter).Decode(&arr)if err != nil { panic(err)}
fmt.Printf("%s\n", arr)個別の値の取得の例: 完全なファイル
注意
セットアップ例
この例では、接続 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 driverpackage 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}詳細情報
クエリフィルターの作成の詳細については、「クエリの指定 」を参照してください。
API ドキュメント
このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。