使用MongoDB的Go Driver

本文使用的是官方驱动,https://github.com/mongodb/mongo-go-driver
,目前是beta版。

  1. 安装
go get github.com/mongodb/mongo-go-driver

会输出如下提示,属于正常情况,可以不用管

package github.com/mongodb/mongo-go-driver: no Go files in $GOPATH/src/github.com/mongodb/mongo-go-driver

官方驱动目前仍有问题,需要把github.com/mongodb/mongo-go-driver目录拷贝到go.mongodb.org/mongo-driver才能用。

  1. 连接
package main

import (
    "context"
    "fmt"
    "log"
    "time"

    //"github.com/mongodb/mongo-go-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

type Trainer struct {
    Name string
    Age  int
    City string
}

func main() {
    ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
    client, err := mongo.Connect(ctx, &options.ClientOptions{Hosts: []string{"localhost:27017"}})

    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 MongoDB!")

    collection := client.Database("test").Collection("trainers")
    _ = collection

    err = client.Disconnect(context.TODO())

    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Connection to MongoDB closed.")
}

参考:
https://www.mongodb.com/blog/post/mongodb-go-driver-tutorial

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • # Python 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列...
    小迈克阅读 3,034评论 1 3
  • 推荐阅读 MongoDB 资源、库、工具、应用程序精选列表中文版 有哪些鲜为人知,但是很有意思的网站? 一份攻城狮...
    guanguans阅读 982评论 0 6
  • # Awesome Python [![Awesome](https://cdn.rawgit.com/sindr...
    emily_007阅读 2,227评论 0 3
  • 虽然在你身旁你会走得顺利更多,但是, 为了让你走得更远, 我必须要放手, 让你自己在失去搀扶的情况下也走得更稳。 ...
    张洲泽_阅读 174评论 0 0
  • 红妆十里,锣鼓喧天。 迎亲的队伍一路走着,谁都没有注意道,就在那一个刻,一抹红影飞快地向街中小巷跑去。“哼年过半百...
    顾惜颜阅读 184评论 4 4