main.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package main
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "go.mongodb.org/mongo-driver/mongo"
  7. "go.mongodb.org/mongo-driver/mongo/options"
  8. "go.uber.org/zap"
  9. "log"
  10. "os"
  11. )
  12. // 创建一个文件用于日志输出
  13. func logFile() *os.File {
  14. file, err := os.Create("logfile.log")
  15. if err != nil {
  16. log.Fatal("Error creating log file: ", err)
  17. }
  18. return file
  19. }
  20. func main() {
  21. zap.S().Infof("hello world")
  22. // 设置MongoDB连接选项
  23. clientOptions := options.Client().ApplyURI("mongodb://120.46.150.226:27277").SetAuth(options.Credential{
  24. Username: "root",
  25. Password: "root",
  26. })
  27. // 连接到MongoDB
  28. client, err := mongo.Connect(context.TODO(), clientOptions)
  29. if err != nil {
  30. zap.S().Infof("err: %v", err)
  31. }
  32. // 检查连接
  33. err = client.Ping(context.TODO(), nil)
  34. if err != nil {
  35. zap.S().Infof("err: %v", err)
  36. }
  37. zap.S().Infof("Connected to MongoDB!")
  38. // 获取对特定数据库和集合的引用
  39. collection := client.Database("mydatabase").Collection("mycollection")
  40. collection.Indexes()
  41. // 插入文档
  42. insertResult, err := collection.InsertOne(context.TODO(), map[string]interface{}{
  43. "title": "MongoDB 教程",
  44. "description": "MongoDB 是一个 Nosql 数据库",
  45. "by": "菜鸟教程",
  46. "url": "http://www.runoob.com",
  47. "tags": "['mongodb', 'database', 'NoSQL']",
  48. "likes": 100,
  49. })
  50. if err != nil {
  51. zap.S().Infof("err: %v", err)
  52. }
  53. zap.S().Infof("Inserted a single document: %v", insertResult.InsertedID)
  54. // 查询文档
  55. re, err := collection.Find(context.TODO(), map[string]interface{}{"title": "MongoDB 教程"}, options.Find().SetLimit(10).SetSkip(1).SetSort(1))
  56. if err != nil {
  57. zap.S().Infof("err: %v", err)
  58. }
  59. marshal, err := json.Marshal(re)
  60. fmt.Println("Found document:", string(marshal))
  61. /*// 更新文档
  62. updateResult, err := collection.UpdateOne(
  63. context.TODO(),
  64. map[string]interface{}{"title": "MongoDB 教程"},
  65. marshal,
  66. )
  67. if err != nil {
  68. log.Fatal(err)
  69. }
  70. fmt.Printf("Matched %v document and modified %v document(s)\n", updateResult.MatchedCount, updateResult.ModifiedCount)*/
  71. // 删除文档
  72. deleteResult, err := collection.DeleteMany(context.TODO(), map[string]interface{}{"title": "MongoDB 教程"})
  73. if err != nil {
  74. log.Fatal(err)
  75. }
  76. fmt.Printf("Deleted %v document\n", deleteResult.DeletedCount)
  77. // 断开连接
  78. err = client.Disconnect(context.TODO())
  79. if err != nil {
  80. zap.S().Infof("err: %v", err)
  81. }
  82. fmt.Println("Connection to MongoDB closed.")
  83. }