コレクションから単一のドキュメントを取得するには、FindOne() メソッドを使用します。
例
Tip
この例を実行する方法については、「使用例」をお読みください。
この例では、 restaurants コレクション内のドキュメントのモデルとして次の Restaurant 構造体を使用します。
type Restaurant struct { ID primitive.ObjectID `bson:"_id"` Name string RestaurantId string `bson:"restaurant_id"` Cuisine string Address interface{} Borough string Grades []interface{}}次の例では、name が「Bagels N Buns」である restaurants コレクション内のドキュメントに一致しており、一致した最初のドキュメントを返しています。
coll := client.Database("sample_restaurants").Collection("restaurants")
// Creates a query filter to match documents in which the "name" is// "Bagels N Buns"filter := bson.D{{"name", "Bagels N Buns"}}
// Retrieves the first matching documentvar result Restauranterr = coll.FindOne(context.TODO(), filter).Decode(&result)
// Prints a message if no documents are matched or if any// other errors occur during the operationif err != nil { if err == mongo.ErrNoDocuments { return } panic(err)}期待される結果
完全な例を実行すると、次のドキュメントが出力されます。これは、result 変数に Restaurant 構造体として保存されます。
// results truncated{ "ID": "5eb3d668b31de5d588f42950", "Name": "Bagels N Buns", "RestaurantId": "40363427" "Address": [...], "Borough": "Staten Island", "Cuisine": "Delicatessen", "Grades": [...]}詳細情報
クエリフィルターの指定と潜在的なエラーの処理の詳細については、「データの取得」を参照してください。
クエリ演算子の詳細については、MongoDB クエリ演算子のリファレンス ドキュメントを参照してください。