查找多个文档
您可以通过使用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{} }
以下示例匹配 restaurants
集合中 cuisine
为 "Italian"
的文档,返回一个引用匹配文档的游标,然后将文档解包到一个切片中
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 filter cursor, err := coll.Find(context.TODO(), filter) if err != nil { panic(err) } // Unpacks the cursor into a slice var results []Restaurant if err = cursor.All(context.TODO(), &results); err != nil { panic(err) }
查看一个完全可运行的示例
预期结果
运行完整示例将打印以下文档,这些文档存储在 results
变量中,作为 Restaurant
结构体
// results truncated ... { ... , "Name" : "Epistrophy Cafe", "RestaurantId": "41117553", "Cuisine" : "Italian", ... }, { ... , "Name" : "Remi", "RestaurantId": "41118090", "Cuisine" : "Italian", ... }, { ... , "Name" : "Sant Ambroeus", "RestaurantId": "41120682", "Cuisine" : "Italian", ... }, ...
更多信息
要了解如何指定查询过滤器和处理潜在的错误,请参阅检索数据。
要了解查询运算符的更多信息,请参阅MongoDB查询运算符参考文档。