How to convert string to mongoDB.Bson.ObjectId

5,248 views
Skip to first unread message

mscsf...@pucit.edu.pk

unread,
Jun 10, 2014, 5:49:24 AM6/10/14
to mongod...@googlegroups.com

I am working in Asp.net C# and database is MongoDb, I want to convert the userID (entered by console) to ObjectId.

ObjectId userId = System.Console.ReadLine();

How it can be done ?

William Berkeley

unread,
Jun 30, 2014, 1:10:47 PM6/30/14
to mongod...@googlegroups.com
Hi. An ObjectId is a special 12-byte BSON type constructed from a timestamp, a machine id, a process id, and a counter value. There is no general way to convert an arbitrary input string into an ObjectId; it must already be in the right format.

Why do you want to convert the userId to an ObjectId? If you tell us more about your use case there might be a better way to achieve what you are trying to do.

-Will

William Zola

unread,
Jul 1, 2014, 11:45:55 AM7/1/14
to mongod...@googlegroups.com
Hi!

You seem to be under the impression that the _id of a document must be an ObjectID.  This is not the case.  You can use anything you like as the Primary Key of a document.  If the userID is guaranteed to be unique, you can use it as the Primary Key of the document by storing it in the _id field, unmodified.

 -William 

Robert Stam

unread,
Jul 1, 2014, 5:34:13 PM7/1/14
to mongod...@googlegroups.com
You can convert a string (assuming it is in the proper format of course) to an ObjectId as follows:

var userIdString = Console.ReadLine();
var userId = new ObjectId(userIdString);



--
You received this message because you are subscribed to the Google Groups "mongodb-user"
group.
 
For other MongoDB technical support options, see: http://www.mongodb.org/about/support/.
---
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongodb-user...@googlegroups.com.
To post to this group, send email to mongod...@googlegroups.com.
Visit this group at http://groups.google.com/group/mongodb-user.
To view this discussion on the web visit https://groups.google.com/d/msgid/mongodb-user/59a43f6f-f10c-40a6-9fea-d661f4754439%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages