Ofir
Ofir

Reputation: 5279

MongoDB - how to deserialize collection to List<Dictionary<string, object>>

I'm switching my application from working with SQL Server to MongoDB. One of the main reason for doing it is the possibility to use structure-less collections. In my "SQL Version" I had object named RawSensorMessage which contained many properties and most of them were empty at most cases. So when I moved into Mongo I changed RawSensorMessage definition to the following one:

   [DataContract]
    public class RawSensorMessage
    {
        [DataMember]
        public Dictionary<string, object> Data { get; set; }
    }

Assume Inside Mongo I have a collection with many records which each one contains different properties. When I query this collection, I don't want to map it to a strongly type object, I want to query it to a 'RawSensorMessage' object (means to fill the 'Data' dictionary inside with the properties and values).

How should I do it? Is it accepted approach to work with structure-less collections?

Upvotes: 0

Views: 2528

Answers (1)

BendEg
BendEg

Reputation: 21088

A solution would be to cast your BSON document which you get from the MongoDB to an JSON object: ToJSON() After that you can serialize your JSON object to a dictionary, like this:

var result = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

Hope this help.

Upvotes: 1

Related Questions