使用 mongo go 驱动程序查找集合中的所有文档

如何使用 mongo-go-driver 查找集合中的所有文档?


我尝试通过nil过滤器,但这不会返回任何文档,而是返回nil. 我还检查了文件,但没有看到任何关于归还所有文件的提及。这是我尝试过的上述结果。


client, err := mongo.Connect(context.TODO(), "mongodb://localhost:27017")

coll := client.Database("test").Collection("albums")

if err != nil { fmt.Println(err) }

// we can assume we're connected...right?

fmt.Println("connected to mongodb")


var results []*Album

findOptions := options.Find()

cursor, err := coll.Find(context.TODO(), nil, findOptions)

if err != nil {

   fmt.Println(err) // prints 'document is nil'

}

findOptions另外,我对为什么我在调用集合上的函数时需要指定Find()(或者我不需要指定?)感到困惑。


守候你守候我
浏览 184回答 2
2回答

慕姐4208626

这是我使用 golang 的官方 MongoDB 驱动程序得出的结果。//Find multiple documentsfunc 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)}

qq_笑_17

尝试传递一个空的bson.D而不是nil:cursor, err := coll.Find(context.TODO(), bson.D{})另外,FindOptions是可选的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go