简体   繁体   中英

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?

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")
}
>

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