Insert Dictionary into MongoDB with c# driver

后端 未结 1 1560

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 Bs

相关标签:
1条回答
  • 2021-02-04 08:07

    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")
    }
    >
    
    0 讨论(0)
提交回复
热议问题