Go学习:[email protected]模块遍历查询Mongodb表(Find)

示例:

package main

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"gopkg.in/mgo.v2/bson"
	"log"
	"time"
)

type Video struct {
	ID    string `json:"id"`
	Title string `json:"title"`
	Type  string `json:"type"`
}

func main() {
	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
	client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://192.168.1.42:27017"))
	collection := client.Database("sample").Collection("media")

	ctx, _ = context.WithTimeout(context.Background(), 30*time.Second)
	cur, err := collection.Find(ctx, bson.M{"type": "电视剧"})
	if err != nil {
		log.Fatal("find:" + err.Error())
	}
	defer cur.Close(ctx)
	for cur.Next(ctx) {
		var result Video
		err := cur.Decode(&result)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%s\n", result)
	}
	if err := cur.Err(); err != nil {
		log.Fatal(err)
	}

}
发布了51 篇原创文章 · 获赞 3 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/pengpengzhou/article/details/105222244