使用 mongo go driver 查找集合中的所有文档

Kel*_*let 5 go mongodb mongo-go

我在这里查看了答案但这使用了旧的且未维护的 mgo。如何使用 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'
}
Run Code Online (Sandbox Code Playgroud)

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

Mos*_*vah 8

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

cursor, err := coll.Find(context.TODO(), bson.D{})
Run Code Online (Sandbox Code Playgroud)

此外,FindOptions是可选的。

免责声明:我从未使用过官方驱动程序,但在https://godoc.org/go.mongodb.org/mongo-driver/mongo上有一些示例

好像他们的教程已经过时了:/

  • 这按预期工作了,谢谢。我希望其他人能发现这很有用,因为我的搜索没有结果。 (2认同)
  • @KellyFlet 很高兴提供帮助;押韵很好 xD (2认同)

小智 8

这是我为 golang 使用官方 MongoDB 驱动程序的想法。我正在使用 godotenv ( https://github.com/joho/godotenv ) 来传递数据库参数。

//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)


}
Run Code Online (Sandbox Code Playgroud)