文档菜单
文档首页
/ / /
Go 驱动
/ /

查找文档

您可以使用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查询运算符参考文档。

FindOne()

返回

查找操作