查找文档
您可以使用FindOne()
方法从集合中检索单个文档。
示例
提示
阅读用法示例了解如何运行此示例。
此示例使用以下Restaurant
结构作为restaurants
集合中文档的模型
type Restaurant struct { ID primitive.ObjectID `bson:"_id"` Name string RestaurantId string `bson:"restaurant_id"` Cuisine string Address interface{} Borough string Grades []interface{} }
以下示例匹配restaurants
集合中名称为"Bagels N Buns"的文档,返回第一个匹配的文档
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 document var result Restaurant err = coll.FindOne(context.TODO(), filter).Decode(&result) // Prints a message if no documents are matched or if any // other errors occur during the operation if 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查询运算符参考文档。