go使用mongo

package mongodb

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"log"
)

var (
	client *mongo.Database
)

func init() {
	// Set client options
	clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")


	// Connect to MongoDB
	if clt, err := mongo.Connect(context.TODO(), clientOptions); err != nil {
		log.Fatalln(err)
	} else {
		if err := clt.Ping(context.TODO(), nil); err != nil {
			log.Fatalln(err)
		}
		client = clt.Database("collyproject")

	}
	//collection := client.Collection("users")

	fmt.Println("Connected to MongoDB!")
}

type Collection struct {
	collection *mongo.Collection
	database *mongo.Database
}

func GetConnection() *mongo.Database {
	return client
}
posted @ 2020-10-14 17:28  公众号python学习开发  阅读(161)  评论(0编辑  收藏  举报