Search when id is UUID Binary

706 views
Skip to first unread message

Diego Medina

unread,
Apr 5, 2016, 1:40:36 AM4/5/16
to mgo-users
Hi,

I have an application that uses the java driver to save a java UUID as the _id on a collection. Then I have the string representation of the UUID in Go, and I need to search this collection to get the document from mongoDB

I tried this:

mongoExtSess.Find(bson.M{
"_id": bson.Binary{
Kind: 0x03,
Data: []byte(cookie.Value),
},
}).One(&ext)


cookie.Value is something like `39bc5eba-a25c-4638-90a8-57682885d074`

but this isn't finding anything. I think the problem is that I'm simply converting the string of the UUID into a []byte, but I don't know what's the correct way to do this.

Thanks

Diego

Diego Medina

unread,
Apr 6, 2016, 5:18:02 AM4/6/16
to mgo-users
I figured it out!

First you need one of the uuid libraries foe Go, I used github.com/satori/go.uuid

But turns out that the java driver for MongoDB changes the order of the bytes in the uuid, so you need to reorder them in your go code:


//this is my doc in Mongo
var ext1 struct {
ID        bson.Binary `bson:"_id"`
Expires   time.Time
UserID    bson.ObjectId `bson:"userId"`
CompanyID bson.ObjectId `bson:"companyId"`
}
//cookie.Value has the uuid as string generated by the Java driver
u, err := uuid.FromString(cookie.Value)

if err != nil {
fmt.Printf("Something gone wrong: %s\n\n", err)
}

//Here we match the order the java driver uses
var searchID []byte
for x := 7; x > -1; x-- {
searchID = append(searchID, u[x])
}
for x := 15; x > 7; x-- {
searchID = append(searchID, u[x])
}

mongoExtSess.Find(bson.M{
"_id": bson.Binary{
Kind: 0x03,
Data: searchID[:],
},
}).One(&ext1)

//This works now and it finds the right document
log.Printf("search using uuid: %+v\n", searchID[:])
log.Printf("result: %+v\n", ext1.ID)



Thank you.
Reply all
Reply to author
Forward
0 new messages