简体   繁体   中英

How to parse ObjectId of dynamic type in .NET MongoDb Driver

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM