Bsonizing Guids in C#

1,608 views
Skip to first unread message

Dan Terrill

unread,
Jul 21, 2011, 4:39:24 PM7/21/11
to mongod...@googlegroups.com
The ID for my "Student" object is a Guid that's stored like this:

> db.Students.findOne({FirstName:'Toral'})
{
        "_id" : BinData(3,"YS5eUsfjXE+GT5Nl5+9CIw=="),


I have a reference to that ID in another user (yeah, I know, it wasn't my call). It's stored as the Guid ToString, so we get something like this>

> db.SiteUsers.findOne({Username:'Toral'})
{
        "_id" : BinData(3,"erAlL11vYUmLFrrE48abdg=="),
        "StudentId" : "525e2e61-e3c7-4f5c-864f-9365e7ef4223",




Given the string "525e2e61-e3c7-4f5c-864f-9365e7ef4223", how can I query for BinData(3,"YS5eUsfjXE+GT5Nl5+9CIw==") ?

Robert Stam

unread,
Jul 21, 2011, 4:45:47 PM7/21/11
to mongodb-user
In C#, you can write something like:

var studentId = Guid.Parse(siteUser["StudentId"].AsString);
var student = students.FindOne(Query.EQ("_id", studentId);

In the Mongo shell it's much much harder right now.

Dan Terrill

unread,
Jul 21, 2011, 4:48:46 PM7/21/11
to mongod...@googlegroups.com
Ah, thanks! I was trying to do it backwards -- parse the Guid into something Mongo understands

--
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To post to this group, send email to mongod...@googlegroups.com.
To unsubscribe from this group, send email to mongodb-user...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/mongodb-user?hl=en.


Robert Stam

unread,
Jul 21, 2011, 4:56:40 PM7/21/11
to mongodb-user
The reason that code works is that there is an automatic conversion
from Guid to BsonBinaryData, so the query is really equivalent to:

Query.EQ("_id", BsonBinaryData.Create(studentId))

So the studentId of type Guid is automatically converted to an
instance of BsonBinaryData.
Reply all
Reply to author
Forward
0 new messages