查看: 25|回覆: 0

golang操作mongodb

[複製鏈接]

4

主題

0

回帖

0

積分

热心网友

金币
0
閲讀權限
220
精華
0
威望
0
贡献
0
在線時間
0 小時
註冊時間
2009-6-20
發表於 2020-1-8 15:56:00 | 顯示全部樓層 |閲讀模式

 

package main

import (
    "fmt"
    "go.mongodb.org/mongo-driver/mongo"
    "context"
    "go.mongodb.org/mongo-driver/mongo/options"
    "go.mongodb.org/mongo-driver/bson/primitive"
    "time"
)


// 任务的执行时间点
type TimePoint struct {
    StartTime int64    `bson:"startTime"`
    EndTime int64    `bson:"endTime"`
}


// 一条日志
type LogRecord struct {
    JobName string    `bson:"jobName"` // 任务名
    Command string `bson:"command"` // shell命令
    Err string `bson:"err"` // 脚本错误
    Content string `bson:"content"`// 脚本输出
    TimePoint TimePoint `bson:"timePoint"`// 执行时间点
}

func main(){
    var (
        client *mongo.Client
        err error
        result *mongo.InsertOneResult
    )

    // 建立mongodb连接
    clientOptions := options.Client().ApplyURI("mongodb://ichunt:huntmon6699@192.168.1.237:27017/ichunt?authMechanism=SCRAM-SHA-1")
    if client, err = mongo.Connect(
        context.TODO(),clientOptions); err != nil {
        return
    }

    // 2, 选择数据库my_db
    database := client.Database("ichunt")

    // 3, 选择表my_collection
    collection := database.Collection("cron_log")
    // 4, 插入记录(bson)
    record := &LogRecord{
        JobName: "job10",
        Command: "echo hello",
        Err: "",
        Content: "hello",
        TimePoint: TimePoint{StartTime: time.Now().Unix(), EndTime: time.Now().Unix() + 10},
    }

    if result, err = collection.InsertOne(context.TODO(), record); err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println(result)

    //// _id: 默认生成一个全局唯一ID, ObjectID:12字节的二进制
    docId := result.InsertedID.(primitive.ObjectID)
    fmt.Println("自增ID:", docId.Hex())
}

 

返回:

&{ObjectID("5e158ad09a14bfe14880829b")}
自增ID: 5e158ad09a14bfe14880829b

 

回覆

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即注册

本版積分規則

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部