123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- package test
- import (
- "context"
- "fmt"
- "go.mongodb.org/mongo-driver/bson"
- "go.mongodb.org/mongo-driver/mongo"
- "go.mongodb.org/mongo-driver/mongo/options"
- "log"
- "testing"
- "time"
- )
- var (
- Mongodb_Url = "mongodb://192.168.11.77:27017"
- Mongodb_DB = "aaa"
- Mongodb_Username = "aaa"
- Mongodb_Password = "aaaaaaaaa"
- )
- func Connect() (*mongo.Database, error) {
- credential := options.Credential{
- AuthSource: Mongodb_DB,
- Username: Mongodb_Username,
- Password: Mongodb_Password,
- }
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
- defer cancel()
- client, err := mongo.Connect(ctx, options.Client().ApplyURI(Mongodb_Url).SetAuth(credential).SetMaxPoolSize(10))
- if err != nil {
- log.Print(err)
- }
- return client.Database(Mongodb_DB), err
- }
- func TestNamex(t *testing.T) {
- // 连接到MongoDB
- DB, err := Connect()
- if err != nil {
- panic(any(err))
- }
- collection := DB.Collection("aaa")
- _, err = collection.InsertOne(context.TODO(), bson.D{{"text", "text"}})
- if err != nil {
- t.Fatalf("error inserting: %v", err)
- }
- students := []interface{}{bson.D{{"text", "2text"}}, bson.D{{"text", "1text"}}}
- insertManyResult, err := collection.InsertMany(context.TODO(), students)
- if err != nil {
- panic(any(err))
- }
- fmt.Println("Inserted multiple documents: ", insertManyResult.InsertedIDs)
- }
- func Data_Add(JointTab string, bson_r *bson.M) {
- // 连接到MongoDB
- DB, err := Connect()
- if err != nil {
- panic(any(err))
- }
- //fmt.Println("JointTab:", JointTab)
- collection := DB.Collection(JointTab)
- _, err = collection.InsertOne(context.TODO(), bson_r)
- if err != nil {
- panic(any(err))
- }
- //
- //students := []interface{}{bson.D{{"text", "2text"}}, bson.D{{"text", "1text"}}}
- //insertManyResult, err := collection.InsertMany(context.TODO(), students)
- //if err != nil {
- // panic(any(err))
- //}
- //fmt.Println("Inserted multiple documents: ", insertManyResult.InsertedIDs)
- }
|