duanqiongdu9916
2019-02-25 23:21
浏览 702

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

I checked out the answer here but this uses the old and unmaintained mgo. How can I find all documents in a collection using the mongo-go-driver?

I tried passing a nil filter, but this does not return any documents and instead returns nil. I also checked the documentation but did not see any mention of returning all documents. Here is what I've tried with aforementioned result.

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'
}

Also, I'm about confused about why I need to specify findOptions when I've called the Find() function on the collection (or do I not need to specify?).

图片转代码服务由CSDN问答提供 功能建议

我签出了答案,但这使用的是旧的且未维护的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)} 
 //我们可以假设我们已经连接好了吗... \?  nfmt.Println(“ connected to mongodb”)
 
var结果[] *相册
findOptions:= options.Find()
cursor,err:= coll.Find(context.TODO(),nil,findOptions)
if  err!= nil {
 fmt.Println(err)//打印'document is nil'
} 
   
 
 

此外,我对为什么感到困惑 当我在集合上调用了 Find()函数时,我需要指定 findOptions (或者我不需要指定吗?)。 < / DIV>

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doude1917 2019-02-25 23:30
    已采纳

    Try passing an empty bson.D instead of nil:

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

    Also, FindOptions is optional.

    Disclaimer: I've never used the official driver, but there are a few examples at https://godoc.org/go.mongodb.org/mongo-driver/mongo

    Seems like their tutorial is outdated :/

    已采纳该答案
    打赏 评论
  • dpa55065 2019-09-25 08:44

    Here is what I came up with using the official MongoDB driver for golang. I am using godotenv (https://github.com/joho/godotenv) to pass the database parameters.

    //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
    ", results)
    
    
    }
    
    打赏 评论

相关推荐 更多相似问题