Read Documents From A Collection With Different Structure

We are currently working on a .NET Core application and we are using MongoDB for it. I am using .NET Driver to access the data. All the data we are saving in a collection has different types of data structure.

For example, it has first document which has Name, Phone and a Payload which has embedded document in which we are saving address:
{ “Name”: “TestName”, “Phone”: “23846787”, “Payload”: { “Address”: “TestAddress”, “City”: “TestCity” }, “Active”: true }

Then in the same collection we have another document which has Name, Phone and a Payload which is completely different from first one:

{ “Name”: “TestName2”, “Phone”: “54568765”, “Payload”: { “Weight”: “70”, “Age”: “45”, “Gender”: “Female” } }

Now when we use .NET driver to get both of these records, we get an error because it cannot cast the embedded document into an object (as it doesnt know about the object). We need to tell it, which type of object is the embedded document. But we dont want to do it because we have several types of payload we want to save. I tried using discriminator “_t” but it didn’t help.

Can someone please suggest how we can read the data when we have different elements in the document and also has embedded documents ??

Thank you
JW

Hi @Jason_Widener and welcome to the forum,

You can utilise BsonDocument, which is the default type used for documents. It should be able to handle dynamic documents.

Regards,
Wan.

Thank you for your reply. Yes I can utilize BsonDocument but when I get the BsonDocument, I need to cast it as original object which is not same always. For example, an order has a property of type IPayment which can be CreditCard or Giftcard. In one case payment type can be CreditCard and in another case it can GiftCard. So sometimes its has discriminator as _CreditCard and sometime it has _Giftcard. I can use BsonClassMap.RegisterClassMap but its a big class with several subclasss in the property. I dont want to register every single one of them.