123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- package main
- import (
- "context"
- "encoding/json"
- "fmt"
- "go.mongodb.org/mongo-driver/mongo"
- "go.mongodb.org/mongo-driver/mongo/options"
- "go.uber.org/zap"
- "log"
- "os"
- )
- // 创建一个文件用于日志输出
- func logFile() *os.File {
- file, err := os.Create("logfile.log")
- if err != nil {
- log.Fatal("Error creating log file: ", err)
- }
- return file
- }
- func main() {
- zap.S().Infof("hello world")
- // 设置MongoDB连接选项
- clientOptions := options.Client().ApplyURI("mongodb://120.46.150.226:27277").SetAuth(options.Credential{
- Username: "root",
- Password: "root",
- })
- // 连接到MongoDB
- client, err := mongo.Connect(context.TODO(), clientOptions)
- if err != nil {
- zap.S().Infof("err: %v", err)
- }
- // 检查连接
- err = client.Ping(context.TODO(), nil)
- if err != nil {
- zap.S().Infof("err: %v", err)
- }
- zap.S().Infof("Connected to MongoDB!")
- // 获取对特定数据库和集合的引用
- collection := client.Database("mydatabase").Collection("mycollection")
- collection.Indexes()
- // 插入文档
- insertResult, err := collection.InsertOne(context.TODO(), map[string]interface{}{
- "title": "MongoDB 教程",
- "description": "MongoDB 是一个 Nosql 数据库",
- "by": "菜鸟教程",
- "url": "http://www.runoob.com",
- "tags": "['mongodb', 'database', 'NoSQL']",
- "likes": 100,
- })
- if err != nil {
- zap.S().Infof("err: %v", err)
- }
- zap.S().Infof("Inserted a single document: %v", insertResult.InsertedID)
- // 查询文档
- re, err := collection.Find(context.TODO(), map[string]interface{}{"title": "MongoDB 教程"}, options.Find().SetLimit(10).SetSkip(1).SetSort(1))
- if err != nil {
- zap.S().Infof("err: %v", err)
- }
- marshal, err := json.Marshal(re)
- fmt.Println("Found document:", string(marshal))
- /*// 更新文档
- updateResult, err := collection.UpdateOne(
- context.TODO(),
- map[string]interface{}{"title": "MongoDB 教程"},
- marshal,
- )
- if err != nil {
- log.Fatal(err)
- }
- fmt.Printf("Matched %v document and modified %v document(s)\n", updateResult.MatchedCount, updateResult.ModifiedCount)*/
- // 删除文档
- deleteResult, err := collection.DeleteMany(context.TODO(), map[string]interface{}{"title": "MongoDB 教程"})
- if err != nil {
- log.Fatal(err)
- }
- fmt.Printf("Deleted %v document\n", deleteResult.DeletedCount)
- // 断开连接
- err = client.Disconnect(context.TODO())
- if err != nil {
- zap.S().Infof("err: %v", err)
- }
- fmt.Println("Connection to MongoDB closed.")
- }
|