Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert Dictionary into MongoDB with c# driver

I am in a situation where I can't predict which fields my MongoDB document is going to have. So I can no longer create an object with an _id field of type BsonID. I find it very convenient to create a Dictionary (HashTable) and add my DateTime and String objects inside, as many times as I need it.

I then try to insert the resulting Dictionary object into MongoDb, but default serialization fails.

Here's my object of Type HashTable (like a Dictionary, but with varied types inside):

{ "_id":"",
"metadata1":"asaad",
"metadata2":[],
"metadata3":ISODate("somedatehere")}

And the error from the driver I get is:

Serializer DictionarySerializer expected serialization options of type DictionarySerializationOptions, not DocumentSerializationOptions

I googled it, but couldn't find anything useful. What am I doing wrong?

like image 300
tonysepia Avatar asked Apr 11 '13 17:04

tonysepia


People also ask

How do I add a list in MongoDB?

MongoDB Array of Objects using insert() with ExampleThe “insert” command can also be used to insert multiple documents into a collection at one time. The below code example can be used to insert multiple documents at a time. The output shows that those 3 documents were added to the collection.

What is a MongoDB dictionary?

The purpose of using a dictionary is to insert the un-typed or unspecified object in to the Mongo Database. Because it might be required to store the data into the database that does not have a specific type at compile time. It may be specified at runtime or the user can create any data with his own type.


1 Answers

The driver needs to be able to find the _id field. You could create a C# class that has just two properties: Id and Values.

public class HashTableDocument
{
    public ObjectId Id { get; set; }
    [BsonExtraElements]
    public Dictionary<string, object> Values { get; set; }

}

Note that we have to use Dictionary<string, object> instead of Hashtable.

You could then use code like the following to insert a document:

var document = new HashTableDocument
{
    Id = ObjectId.GenerateNewId(),
    Values = new Dictionary<string, object>
    {
        { "metadata1", "asaad" },
        { "metadata2", new object[0] },
        { "metadata3", DateTime.UtcNow }
    }
};
collection.Insert(document);

We can use the MongoDB shell to confirm that the inserted document has the desired form:

> db.test.find().pretty()
{
        "_id" : ObjectId("518abdd4e447ad1f78f74fb1"),
        "metadata1" : "asaad",
        "metadata2" : [ ],
        "metadata3" : ISODate("2013-05-08T21:04:20.895Z")
}
>
like image 119
Robert Stam Avatar answered Oct 25 '22 00:10

Robert Stam