首先导入需要的包

import (
	"bufio"
	"context"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
	"log"
	"net/http"
	"os"
	"time"
)

然后,开始连接mongodb数据库,本人是在func main()函数里连接的数据库

	opts := options.Client().ApplyURI("mongodb://localhost:27017")

	// 连接数据库
	client, err := mongo.Connect(context.Background(), opts)
	if err != nil {
		log.Fatal(err)
	}

	// 判断服务是不是可用
	if err = client.Ping(context.Background(), readpref.Primary()); err != nil {
		log.Fatal(err)
	}

遍历该数据库的每个集合,首先获取一个mongodb数据库中的所有集合的名字,再进行逐个连接,再查询数据,即整个过程是一个遍历的过程。

//查询数据这块
db_name := "***"
DatabaseNow:=client.Database(db_name)
filter := bson.M{ "name" : "菜鸟教程"}
AllCollections, _ :=DatabaseNow.ListCollectionNames(context.Background(),bson.D{}) //此处可以获得mongodb中数据库中所有集合的名字,以列表的形式返回
ResultsMap := make(map[string] interface{})
for _, collection := range AllCollections{
	ConnectSet := DatabaseNow.Collection(collection)   //连接数据库里的集合
	cursor, _ := ConnectSet.Find(context.Background(),filter)
	defer cursor.Close(context.Background())

	//创建bson.M类型的数组
	var temp []bson.M

	if err = cursor.All(context.Background(),&temp); err != nil {
		log.Fatal(err)
	}
	
	if len(temp) > 0{
		//一个表单创建一个map
		OneConnectSet := make( []interface{},len(temp))
        
        //做相应的处理即可  		

		ResultsMap[collection]=OneConnectSet 
	}
}

数据经过上面的处理后, ResultsMap的类型是map [string] interface{}  由于我们返回前台时,需要json类型的数据,而golang语言中的map [string] interface{}类型是可以转换成json类型的。所以我用了方法

c.JSON(http.StatusOk,gin.H{"date":&ResultsMap})

注意gin.H{"date":&ResultsMap},由于我们在定义ResultsMap时候,使用了make方法给ResultsMap分类了内存,所以此处返回时,要加上&。这里的c.JSON会把后边的转成json格式的数据进行返回。