0

Here's my code. DbContext.Resources is IMongoCollection<dynamic> because it's highly unstructured.

var resource = await DbContext.Resources.Find(
  Builders<dynamic>.Filter.Eq("_id", ObjectId.Parse(id))
).SingleAsync();

And the resulting resource object is

[{
  "_id": {
    "timestamp":1487967980,
    "machine":614561,
    "pid":30862,
    "increment":16022269,
    "creationTime":"2017-02-24T20:26:20Z"
  },
  ...
}]

What is the best practice for parsing this _id?

9
  • Can i ask this ? are you using BSON library that goes with the c# driver to handle all the ser/deser for you. nuget.org/packages/MongoDB.Bson ? Commented May 22, 2017 at 16:04
  • yes, i'm using v=2.4.3 Commented May 22, 2017 at 16:35
  • The only problem is I have nothing to annotate. The type is dynamic. There is no class. Commented May 22, 2017 at 17:16
  • What is the reason to parse that id? Do you want to use it as primary key for application logic? Don't objects in that collection has own unique keys? Commented May 23, 2017 at 9:27
  • for simplicity, why return { _id: { $oid: 'guid' } } when i can just return { _id: 'guid' }. Will there ever be anything else in the object? Why make a complicated api that is obnoxious for developers to use? Commented May 23, 2017 at 9:55

1 Answer 1

2
+200

There is multiples ways to represent and construct an ObjectId. The object returned from your IMongoCollection corresponds to the actual _id value you're seeing in your database encoded using the constructor that can be seen here and composed of the following fields:

  • timestamp (int)
  • machine hash (int)
  • pid (short)
  • increment (int)

An ObjectId should implement a ToString method, allowing you to convert the object into its string representation, but if for some reason you can't use it due to your dynamic typing, you can either create a new one with the constructor, or leverage the ObjectId.Pack method, which would allow you to convert back the timestamp, machine, pid and increment into a byte array which can also be used for the ObjectId creation.

Sign up to request clarification or add additional context in comments.

2 Comments

Is there a best way for handling this in a query with numerous results. I'm concerned that there will be a significant performance problem if I call .ToString() on 1000 records individually.
After looking at multiple resources, I would say the recommended way would be to use annotations. Since that's not something possible in your case, I would do a little wrapping function in charge of iterating over your collection and doing ToString on every item. 1000 items is way below the point performance would be an issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.