checkiz / elixir-mongo

MongoDB driver for Elixir
MIT License
101 stars 31 forks source link

Find by ObjectId #13

Closed trenpixster closed 9 years ago

trenpixster commented 9 years ago

I'm a bit lost as on how to build a ObjectId from a string to use in a find() query. E.g.:

collStrId = "53d2dd594a46c539d100000a"
query = anyColl.find(%{ collection_id: %Bson.ObjectId{oid: collStrId} }).toArray

triggers

(Mongo.Error) %{"$err": "BSONElement: bad type 52", code: 10320}

Thanks!

jerp commented 9 years ago

"53d2dd594a46c539d100000a" is an hexadecimal representation of an ObjectID.

ObjectID is a binary string of size 12, in your case, it is <<83, 210, 221, 89, 74, 70, 197, 57, 209, 0, 0, 10>>

You can use the following code to retrieve the binary from a hex

for <<hex::16 <- "53d2dd594a46c539d100000a">>, into: <<>>, do: <<String.to_integer(<<hex::16>>, 16)::8>>

When inspecting a document, I reformat the ObjectID in hexadecimal so that it looks like what you get in tools like Robomongo. An idea could be to add a convenience function Bson.ObjectId.from_hex that would take a hex string and put it in the right binary format internally. Although, I can't see other use case for this than debugging in iex.

trenpixster commented 9 years ago

Thanks for the explanation @jerp :+1: