对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

查找文档

您可以使用 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 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)}

查看完全可运行的示例

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

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

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

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

FindOne()

给本页内容打分