Skip to content
GitHub Twitter

Handle UUID mongo query in golang

Handle UUID mongo query in golang

In order to query mongodb with csharp guid in golang, you would need the following conversions:

func CsuuidToBinary(key string) []byte {
    hexStr := strings.Replace(key, "-", "", -1)
    first := hexStr[6:8] + hexStr[4:6] + hexStr[2:4] + hexStr[0:2]
    second := hexStr[10:12] + hexStr[8:10]
    third := hexStr[14:16] + hexStr[12:14]
    fourth := hexStr[16:len(hexStr)]
    hexStr = first + second + third + fourth

    data, _ := hex.DecodeString(hexStr)
    return data
}

and to use it with MongoDB Go Driver

binaryKey := CsuuidToBinary("246076cf-b5cf-4d5a-9f15-1d46aa2108a1")

clientOptions := options.Client().ApplyURI("your_mongo_connection_string")
conn.Collection("Test").FindOne(context.Background(), bson.M{"Key": primitive.Binary{Subtype: 0x03, Data: binaryKey}})

and to convert back to GUID from binary:

func BinaryToCSUUID(data []byte) string {
	const byteSize = 16
	if len(data) != byteSize {
		return
	}
	var u [byteSize]byte
	copy(u[:], data)

	buf := make([]byte, 36)

	hex.Encode(buf[0:2], u[3:4])
	hex.Encode(buf[2:4], u[2:3])
	hex.Encode(buf[4:6], u[1:2])
	hex.Encode(buf[6:8], u[0:1])
	buf[8] = '-'
	hex.Encode(buf[9:11], u[5:6])
	hex.Encode(buf[11:13], u[4:5])
	buf[13] = '-'
	hex.Encode(buf[14:16], u[7:8])
	hex.Encode(buf[16:18], u[6:7])
	buf[18] = '-'
	hex.Encode(buf[19:23], u[8:10])
	buf[23] = '-'
	hex.Encode(buf[24:], u[10:])
	return string(buf)
}