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

查找多个文档

您可以使用 Find() 方法查找集合中的多个文档。

提示

参阅“使用示例”,了解如何运行此示例。

此示例使用以下 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{}}

以下示例匹配 cuisine 为 "Italian" 的 restaurants 集合中的文档,并返回一个引用匹配文档的光标,然后将这些文档解压缩成一个切片:

coll := client.Database("sample_restaurants").Collection("restaurants") // Creates a query filter to match documents in which the "cuisine"// is "Italian"filter := bson.D{{"cuisine", "Italian"}} // Retrieves documents that match the query filtercursor, err := coll.Find(context.TODO(), filter)if err != nil { panic(err)} // Unpacks the cursor into a slicevar results []Restaurantif err = cursor.All(context.TODO(), &results); err != nil { panic(err)}

查看完全可运行的示例

运行完整示例会打印以下文档,这些文档作为 Restaurant 结构体存储在 results 变量中:

// results truncated...{ ... , "Name" : "Epistrophy Cafe", "RestaurantId": "41117553", "Cuisine" : "Italian", ... },{ ... , "Name" : "Remi", "RestaurantId": "41118090", "Cuisine" : "Italian", ... },{ ... , "Name" : "Sant Ambroeus", "RestaurantId": "41120682", "Cuisine" : "Italian", ... },...

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

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

给本页内容打分