“文档” 菜单
文档首页
/ / /
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 集合中 name 为“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)
}

查看 完全可运行的示例

运行完整示例会打印以下文档,该文档作为 Restaurant struct 存储在 result 变量中:

// results truncated
{
"ID": "5eb3d668b31de5d588f42950",
"Name": "Bagels N Buns",
"RestaurantId": "40363427"
"Address": [...],
"Borough": "Staten Island",
"Cuisine": "Delicatessen",
"Grades": [...]
}

要了解有关指定查询过滤器和处理潜在错误的更多信息,请参阅检索数据。

要了解有关查询运算符的更多信息,请参阅MongoDB 查询运算符参考文档。

FindOne()

← 查找操作