Search code examples
c#linqmongodbmongodb-querymongodb-.net-driver

How to create a class for a MongoDB collection that is not mine?


I'm new to MongoDB and having some issues. Following this easy guide here (http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-csharp-driver) but I'm instead connecting to a database that I did not personally create. So when the examples include something like:

var collection = database.GetCollection<Entity>("entities");

it doesn't work for the actual database i'm connecting to because I don't have the class. it's full of types that I can't just guess.. for example:

/* 0 */
{
  "_id" : ObjectId("54f0f990cea606d49fafd5h2"),
  "Time" : ISODate("2015-02-27T23:11:12.301Z"),
  "Timecode" : "15:11:12:18",
  "Round" : "1",
  "FighterID" : 5,
  "FighterName" : "John Doe",
  "TypeID" : 1,
  "Type" : "jab",
  "HandID" : 2,
  "Hand" : "left",
  "Force" : 0.0,
  "Velocity" : 8.0789527768068456,
  "Confidence" : 67.689217510307827,
  "ImpactType" : 1,
  "FightID" : "fea5dc60-b898-11e4-ac68-a5f571ea05d9"
}

i don't know how to make a class for that since the class members are rather complicated.

how do i go about doing this?


Solution

  • I am not aware of any way to create the class out of mongodb like we have with EF and linq-to-sql.

    I suggest you do one of two things, and i believe the second solution will harder but closer to what you asking

    1. Try use bsonextractelements attribute to catch all complicated fields

      public MyClass {
       // fields and properties
       [BsonExtraElements]
       public BsonDocument CatchAll { get; set; }
      }
      

      or:

    2. use reflection and store the name of properties as well as the data type of each property to txt file maybe. Then create your class manually.