mongo_test.go 996 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package mhayaMongo
  2. import (
  3. "context"
  4. "fmt"
  5. "testing"
  6. clog "github.com/mhaya/logger"
  7. "go.mongodb.org/mongo-driver/bson"
  8. "go.mongodb.org/mongo-driver/bson/primitive"
  9. )
  10. type Student struct {
  11. Name string
  12. Age int
  13. }
  14. func TestConnect(t *testing.T) {
  15. clog.Info("test connect mongodb")
  16. uri := "mongodb://localhost:27017"
  17. dbName := "test"
  18. mdb, err := CreateDatabase(uri, dbName)
  19. if err != nil {
  20. clog.Warn(err)
  21. return
  22. }
  23. collection := mdb.Collection("numbers")
  24. student := &Student{
  25. Name: "aaa222",
  26. Age: 111,
  27. }
  28. res, err := collection.InsertOne(context.Background(), student)
  29. insertID := res.InsertedID
  30. clog.Infof("id = %v, err = %v", insertID, err)
  31. //id, _ := primitive.ObjectIDFromHex("649160b6c637f5773cc1e818")
  32. id, ok := insertID.(primitive.ObjectID)
  33. if !ok {
  34. return
  35. }
  36. findFilter := bson.M{"_id": id}
  37. findResult := collection.FindOne(context.Background(), findFilter)
  38. findStudent := Student{}
  39. findResult.Decode(&findStudent)
  40. fmt.Println(findStudent)
  41. }