github.com/godaddy-x/freego@v1.0.156/mongo_driver_test.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"github.com/godaddy-x/freego/utils"
     6  	"go.mongodb.org/mongo-driver/bson"
     7  	"go.mongodb.org/mongo-driver/mongo"
     8  	"go.mongodb.org/mongo-driver/mongo/options"
     9  	"go.mongodb.org/mongo-driver/mongo/readpref"
    10  	"log"
    11  	"testing"
    12  )
    13  
    14  func TestMGPipe(t *testing.T) {
    15  	opts := options.Client().ApplyURI("mongodb://localhost:27017")
    16  	// 连接数据库
    17  	client, err := mongo.Connect(context.Background(), opts)
    18  	if err != nil {
    19  		log.Fatal(err)
    20  	}
    21  	// 判断服务是不是可用
    22  	if err := client.Ping(context.Background(), readpref.Primary()); err != nil {
    23  		log.Fatal(err)
    24  	}
    25  	for i := 0; i < 1; i++ {
    26  		// 获取数据库和集合
    27  		blockDB := client.Database("openserver").Collection("ow_block")
    28  		query := make(map[string]interface{}, 0)
    29  		op := &options.FindOptions{}
    30  		op.SetSort(bson.M{"ctime": 1})
    31  		op.SetLimit(5)
    32  		op.SetProjection(bson.M{"_id": 1, "hash": 1})
    33  		cur, err := blockDB.Find(context.Background(), query, op)
    34  		if err != nil {
    35  			log.Fatal(err)
    36  		}
    37  		var result []*OwBlock
    38  		if err := cur.All(context.Background(), &result); err != nil {
    39  			panic(err)
    40  		}
    41  		//fmt.Println(result)
    42  	}
    43  	walletDB := client.Database("openserver").Collection("ow_wallet")
    44  	ctx := context.Background()
    45  	client.UseSession(ctx, func(sessionContext mongo.SessionContext) error {
    46  		if err := sessionContext.StartTransaction(); err != nil {
    47  			panic(err)
    48  		}
    49  		wallet := &OwWallet{
    50  			Id:       utils.NextIID(),
    51  			WalletID: "我要test",
    52  		}
    53  		_, err := walletDB.InsertOne(sessionContext, &wallet)
    54  		if err != nil {
    55  			panic(err)
    56  		}
    57  		_, err = walletDB.InsertOne(sessionContext, &wallet)
    58  		if err != nil {
    59  			panic(err)
    60  		}
    61  		sessionContext.AbortTransaction(sessionContext)
    62  		return nil
    63  	})
    64  }