bson.ObjectIDHex(s string)(ObjectID, error)
primitive,ObjectIDFromHex(s string) (ObjectID, error)
primitive.NewObjectIDFromTimestamp(timestamp time.Time) ObjectID
package main
import (
"context"
"fmt"
"log"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
// 设置客户端连接配置
clientOptions := options.Client().ApplyURI("mongodb://admin:123456@192.168.2.58:27017")
// 连接到MongoDB
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
// 检查连接
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
collection := client.Database("reading").Collection("article1")
// ObjectID('61610bc860e33888399b0a54')
//从Hex String 转换ObjectID
//直接从数据库拷出来的HexString,所以err不接收了
id, _ := primitive.ObjectIDFromHex("61610bc860e33888399b0a54")
fmt.Println(id)
// var m bson.M
var m ReadingArticle
//查找记录,以及decode
err = collection.FindOne(context.TODO(), bson.M{"_id": id}).Decode(&m)
if err != nil {
log.Fatal(err)
}
fmt.Println(m)
}
type ReadingArticle struct {
ID primitive.ObjectID `bson:"_id,omitempty"`
Title string `bson:"title"`
Value string `bson:"value"`
Origin string `bson:"origin"`
Time int `bson:"time"`
Kind string `bson:"kind"`
Link string `bson:"link"`
}