How to generate and store a uuid type 0x04 in mongodb using golang?

huangapple go评论83阅读模式
英文:

How to generate and store a uuid type 0x04 in mongodb using golang?

问题

我正在尝试将一个UUID类型4存储到MongoDB中,但是当我调用InsertOne函数时,它将我的UUID存储为类型0(通用类型),而不是类型4。我不确定我做错了什么。

我的代码:

type Document struct {
	ID         uuid.UUID `bson:"_id" json:"id"`
	FcrID      string    `bson:"fcrId" json:"fcrId"`
	ContextKey string    `bson:"contextKey" json:"contextKey"`
	PrivateKey string    `bson:"privateKey" json:"privateKey"`
	PublicKey  string    `bson:"publicKey" json:"publicKey"`
}

for _, message := range messages {
	body := message.Body
	fmt.Println("new messaged received, writing keys to database")

	id := uuid.New()

	var jsonDocument common.DocumentKey

	err = json.Unmarshal(body, &jsonDocument)
	if err != nil {
		fmt.Println(err)
		return
	}

	d, bsonErr := bson.Marshal(common.Document{
		ID:         id,
		FcrID:      jsonDocument.FcrID,
		ContextKey: jsonDocument.ContextKey,
		PrivateKey: jsonDocument.PrivateKey,
		PublicKey:  jsonDocument.PublicKey,
	})
	if bsonErr != nil {
		fmt.Println(bsonErr)
		return
	}

	err = databaseOperations.InsertData(ctx, mclient, "management", "keys", d)
	if err != nil {
		fmt.Println(err)
		return
	}

	err = receiver.CompleteMessage(context.TODO(), message, nil)
	if err != nil {
		log.Println(err)
	}
}

但是ID被存储为BinData 0,而我希望它是BinData 4。

我知道UUID将返回一个[16]byte,但我不明白为什么MongoDB将其理解为要存储的通用数据,而不是正确的UUID类型0x04。

我该如何让MongoDB将我的UUID存储为类型4而不是0?

谢谢。

英文:

I am trying to store in mongodb a uuid type 4 but when I call the InsertOne function this is storing my uuid as type 0 (generic) and not type 4.
I don't know exactly what I am doing wrong.

My code:

type Document struct {
	ID         uuid.UUID `bson:"_id" json:"id"`
	FcrID      string    `bson:"fcrId" json:"fcrId"`
	ContextKey string    `bson:"contextKey" json:"contextKey"`
	PrivateKey string    `bson:"privateKey" json:"privateKey"`
	PublicKey  string    `bson:"publicKey" json:"publicKey"`
}

for _, message := range messages {
		body := message.Body
		fmt.Println("new messaged received, writing keys to database")

		id := uuid.New()

		var jsonDocument common.DocumentKey

		err = json.Unmarshal(body, &jsonDocument)
		if err != nil {
			fmt.Println(err)
			return
		}

		d, bsonErr := bson.Marshal(common.Document{
			ID:         id,
			FcrID:      jsonDocument.FcrID,
			ContextKey: jsonDocument.ContextKey,
			PrivateKey: jsonDocument.PrivateKey,
			PublicKey:  jsonDocument.PublicKey,
		})
		if bsonErr != nil {
			fmt.Println(bsonErr)
			return
		}

		err = databaseOperations.InsertData(ctx, mclient, "management", "keys", d)
		if err != nil {
			fmt.Println(err)
			return
		}

		err = receiver.CompleteMessage(context.TODO(), message, nil)
		if err != nil {
			log.Println(err)
		}
	}

but the id is being stored as BinData 0 but I would like to have BinData 4.

I know uuid will return a [16]byte but I don't understand why mongo is understanding it as a generic data to be stored and not as a proper uuid type 0x04.

how can I make mongodb store my uuid as type 4 and not 0?

Thank you

答案1

得分: 2

它起作用了,非常简单

类型 Document struct {
    ID         primitive.Binary `bson:"_id" json:"id"`
    FcrID      string           `bson:"fcrId" json:"fcrId"`
    ContextKey string           `bson:"contextKey" json:"contextKey"`
    PrivateKey string           `bson:"privateKey" json:"privateKey"`
    PublicKey  string           `bson:"publicKey" json:"publicKey"`
}

id := uuid.New()

binId := primitive.Binary{
    Subtype: 0x04,
    Data:    id[:],
}
英文:

it worked, very simple

type Document struct {
ID         primitive.Binary `bson:"_id" json:"id"`
FcrID      string           `bson:"fcrId" json:"fcrId"`
ContextKey string           `bson:"contextKey" json:"contextKey"`
PrivateKey string           `bson:"privateKey" json:"privateKey"`
PublicKey  string           `bson:"publicKey" json:"publicKey"`
}

    id := uuid.New()

	binId := primitive.Binary{
		Subtype: 0x04,
		Data:    id[:],
	}

答案2

得分: 0

如果你想在使用Golang的MongoDB中将UUID存储为0x04类型,你需要确保在插入数据库之前将UUID正确序列化为二进制子类型0x04

下面是一个示例代码片段,展示了如何生成类型为0x04的UUID并将其存储在MongoDB中:

import (
    "github.com/google/uuid"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
)

// 定义文档结构
type Document struct {
    ID         uuid.UUID `bson:"_id" json:"id"`
    FcrID      string    `bson:"fcrId" json:"fcrId"`
    ContextKey string    `bson:"contextKey" json:"contextKey"`
    PrivateKey string    `bson:"privateKey" json:"privateKey"`
    PublicKey  string    `bson:"publicKey" json:"publicKey"`
}

func main() {

    // 创建一个类型为0x04的新UUID
    id := uuid.New()
    
    // 将UUID序列化为二进制子类型0x04
    idBytes := id.Bytes()
    idBytes[6] = (idBytes[6] & 0x0f) | 0x40 // 将版本字节设置为4
    idBytes[8] = (idBytes[8] & 0x3f) | 0x80 // 将变体字节设置为RFC 4122变体
    idBinary := bson.Binary{
        Subtype: 0x04,
        Data:    idBytes,
    }
    fmt.Println("idBinary:", idBinary)

    // 创建一个新的文档实例
    doc := &Document{
        ID:         uuid.Nil, // ID将由MongoDB自动生成
        FcrID:      "my-fcr-id",
        ContextKey: "my-context-key",
        PrivateKey: "my-private-key",
        PublicKey:  "my-public-key",
    }
    
    fmt.Println("doc:", doc)
    // 将文档序列化为BSON
    bsonDoc, err := bson.Marshal(doc)
    if err != nil {
        fmt.Println("~ marshal: err:", err)
    }

    // 将ID字段设置为二进制UUID值
    bsonDoc[4] = 0x04 // 将ID字段的BSON类型设置为二进制
    bsonDoc = append(bsonDoc[:5], idBinary.Bytes()...)
    bsonDoc = append(bsonDoc, 0x00) // 在BSON文档末尾添加空终止符

    // 使用insertOne()命令将文档插入MongoDB集合
    collection := mclient.Database("MyDB").Collection("MyCollection")
    _, err = collection.InsertOne(ctx, bsonDoc)
    if err != nil {
        fmt.Println("~ insertOne(): err:", err)
    }
}

首先使用uuid.New()函数生成一个新的UUID。然后,通过将版本字节设置为4和变体字节设置为RFC 4122变体,将UUID序列化为二进制子类型0x04。
创建一个新的文档实例并使用bson.Marshal()函数将其序列化为BSON。最后,将ID字段设置为二进制UUID值,并使用collection.InsertOne()函数将文档插入MongoDB集合。

英文:

if you want to store a UUID as type 0x04 in MongoDB using Golang, you need to ensure that the UUID is properly serialized as a binary subtype 0x04 before being inserted into the database.
here, i can give you an example code snippet that shows how to generate a UUID type 0x04 and store it in MongoDB:

Sample Code

import (
"github.com/google/uuid"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)
// Defined my document struct
type Document struct {
ID         uuid.UUID `bson:"_id" json:"id"`
FcrID      string    `bson:"fcrId" json:"fcrId"`
ContextKey string    `bson:"contextKey" json:"contextKey"`
PrivateKey string    `bson:"privateKey" json:"privateKey"`
PublicKey  string    `bson:"publicKey" json:"publicKey"`
}
func main() {
// then, Create a new UUID of type 0x04
id := uuid.New()
// Serialize the UUID as a binary subtype 0x04
idBytes := id.Bytes()
idBytes[6] = (idBytes[6] & 0x0f) | 0x40 // Set the version byte to 4
idBytes[8] = (idBytes[8] & 0x3f) | 0x80 // Set the variant byte to the RFC 4122 variant
idBinary := bson.Binary{
Subtype: 0x04,
Data:    idBytes,
}
fmt.Println("🚀  idBinary : ", idBinary)
// now, Create a new document instance
doc := &Document{
ID:         uuid.Nil, // this, ID will be automatically generated by MongoDB
FcrID:      "my-fcr-id",
ContextKey: "my-context-key",
PrivateKey: "my-private-key",
PublicKey:  "my-public-key",
}
fmt.Println("🚀  doc : ", doc)
// Serialize the document to BSON
bsonDoc, err := bson.Marshal(doc)
if err != nil {
fmt.Println("🚀 ~ marshal : ~ err : ", err)
}
// Set the ID field to the binary UUID value
bsonDoc[4] = 0x04 // Set the BSON type for the ID field to binary
bsonDoc = append(bsonDoc[:5], idBinary.Bytes()...)
bsonDoc = append(bsonDoc, 0x00) // Add a null terminator to the BSON document
// Insert the document into the MongoDB collection using insertOne() command
collection := mclient.Database("MyDB").Collection("MyCollection")
_, err = collection.InsertOne(ctx, bsonDoc)
if err != nil {
fmt.Println("🚀 ~ insertOne(): ~ err : ", err)
}
}

you first generate a new UUID using the uuid.New() function. then, you serialize the UUID as a binary subtype 0x04 by setting the version byte to 4 and the variant byte to the RFC 4122 variant.
you create a new document instance and serialize it to BSON using the bson.Marshal() function. Finally, you set the ID field to the binary UUID value and insert the document into the MongoDB collection using the collection.InsertOne() function.

huangapple
  • 本文由 发表于 2023年4月20日 20:31:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76064080.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定