为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
守候你守候我 2023-06-12 14:25:46
如何使用 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 []*AlbumfindOptions := options.Find()cursor, err := coll.Find(context.TODO(), nil, findOptions)if err != nil {   fmt.Println(err) // prints 'document is nil'}findOptions另外,我对为什么我在调用集合上的函数时需要指定Find()(或者我不需要指定?)感到困惑。
查看完整描述

2 回答

?
慕姐4208626

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)



}


查看完整回答
反对 回复 2023-06-12
?
qq_笑_17

TA贡献1818条经验 获得超7个赞

尝试传递一个空的bson.D而不是nil

cursor, err := coll.Find(context.TODO(), bson.D{})

另外,FindOptions是可选的。

查看完整回答
反对 回复 2023-06-12
  • 2 回答
  • 0 关注
  • 183 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号