2 回答

TA貢獻1852條經驗 獲得超7個贊
這是我使用 golang 的官方 MongoDB 驅動程序得出的結果。
//Find multiple documents
func FindRecords() {
? ? err := godotenv.Load()
? ? if err != nil {
? ? ? ? fmt.Println(err)
? ? }
? ? //Get database settings from env file
? ? //dbUser := os.Getenv("db_username")
? ? //dbPass := os.Getenv("db_pass")
? ? dbName := os.Getenv("db_name")
? ? docCollection := "retailMembers"
? ? dbHost := os.Getenv("db_host")
? ? dbPort := os.Getenv("db_port")
? ? dbEngine := os.Getenv("db_type")
? ? //set client options
? ? clientOptions := options.Client().ApplyURI("mongodb://" + dbHost + ":" + dbPort)
? ? //connect to MongoDB
? ? client, err := mongo.Connect(context.TODO(), clientOptions)
? ? if err != nil {
? ? ? ? log.Fatal(err)
? ? }
? ? //check the connection
? ? err = client.Ping(context.TODO(), nil)
? ? if err != nil {
? ? ? ? log.Fatal(err)
? ? }
? ? fmt.Println("Connected to " + dbEngine)
? ? db := client.Database(dbName).Collection(docCollection)
? ? //find records
? ? //pass these options to the Find method
? ? findOptions := options.Find()
? ? //Set the limit of the number of record to find
? ? findOptions.SetLimit(5)
? ? //Define an array in which you can store the decoded documents
? ? var results []Member
? ? //Passing the bson.D{{}} as the filter matches? documents in the collection
? ? cur, err := db.Find(context.TODO(), bson.D{{}}, findOptions)
? ? if err !=nil {
? ? ? ? log.Fatal(err)
? ? }
? ? //Finding multiple documents returns a cursor
? ? //Iterate through the cursor allows us to decode documents one at a time
? ? for cur.Next(context.TODO()) {
? ? ? ? //Create a value into which the single document can be decoded
? ? ? ? var elem Member
? ? ? ? err := cur.Decode(&elem)
? ? ? ? if err != nil {
? ? ? ? ? ? log.Fatal(err)
? ? ? ? }
? ? ? ? results =append(results, elem)
? ? }
? ? if err := cur.Err(); err != nil {
? ? ? ? log.Fatal(err)
? ? }
? ? //Close the cursor once finished
? ? cur.Close(context.TODO())
? ? fmt.Printf("Found multiple documents: %+v\n", results)
}

TA貢獻1818條經驗 獲得超7個贊
嘗試傳遞一個空的bson.D
而不是nil
:
cursor,?err?:=?coll.Find(context.TODO(),?bson.D{})
另外,FindOptions
是可選的。
- 2 回答
- 0 關注
- 168 瀏覽
添加回答
舉報