mongodb_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package test
  2. import (
  3. "context"
  4. "fmt"
  5. "go.mongodb.org/mongo-driver/bson"
  6. "go.mongodb.org/mongo-driver/mongo"
  7. "go.mongodb.org/mongo-driver/mongo/options"
  8. "log"
  9. "testing"
  10. "time"
  11. )
  12. var (
  13. Mongodb_Url = "mongodb://192.168.11.77:27017"
  14. Mongodb_DB = "aaa"
  15. Mongodb_Username = "aaa"
  16. Mongodb_Password = "aaaaaaaaa"
  17. )
  18. func Connect() (*mongo.Database, error) {
  19. credential := options.Credential{
  20. AuthSource: Mongodb_DB,
  21. Username: Mongodb_Username,
  22. Password: Mongodb_Password,
  23. }
  24. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  25. defer cancel()
  26. client, err := mongo.Connect(ctx, options.Client().ApplyURI(Mongodb_Url).SetAuth(credential).SetMaxPoolSize(10))
  27. if err != nil {
  28. log.Print(err)
  29. }
  30. return client.Database(Mongodb_DB), err
  31. }
  32. func TestNamex(t *testing.T) {
  33. // 连接到MongoDB
  34. DB, err := Connect()
  35. if err != nil {
  36. panic(any(err))
  37. }
  38. collection := DB.Collection("aaa")
  39. _, err = collection.InsertOne(context.TODO(), bson.D{{"text", "text"}})
  40. if err != nil {
  41. t.Fatalf("error inserting: %v", err)
  42. }
  43. students := []interface{}{bson.D{{"text", "2text"}}, bson.D{{"text", "1text"}}}
  44. insertManyResult, err := collection.InsertMany(context.TODO(), students)
  45. if err != nil {
  46. panic(any(err))
  47. }
  48. fmt.Println("Inserted multiple documents: ", insertManyResult.InsertedIDs)
  49. }
  50. func Data_Add(JointTab string, bson_r *bson.M) {
  51. // 连接到MongoDB
  52. DB, err := Connect()
  53. if err != nil {
  54. panic(any(err))
  55. }
  56. //fmt.Println("JointTab:", JointTab)
  57. collection := DB.Collection(JointTab)
  58. _, err = collection.InsertOne(context.TODO(), bson_r)
  59. if err != nil {
  60. panic(any(err))
  61. }
  62. //
  63. //students := []interface{}{bson.D{{"text", "2text"}}, bson.D{{"text", "1text"}}}
  64. //insertManyResult, err := collection.InsertMany(context.TODO(), students)
  65. //if err != nil {
  66. // panic(any(err))
  67. //}
  68. //fmt.Println("Inserted multiple documents: ", insertManyResult.InsertedIDs)
  69. }