問題描述
我無法預測我的 MongoDB 文檔將包含哪些字段.所以我不能再用 BsonID
類型的 _id
字段創建對象.我發現創建一個 Dictionary (HashTable) 并在其中添加我的 DateTime 和 String 對象非常方便,我需要多少次都可以.
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.
然后我嘗試將生成的 Dictionary 對象插入 MongoDb,但默認序列化失敗.
I then try to insert the resulting Dictionary object into MongoDb, but default serialization fails.
這是我的 HashTable 類型對象(類似于字典,但里面有不同的類型):
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 期望 DictionarySerializationOptions 類型的序列化選項,而不是 DocumentSerializationOptions
Serializer DictionarySerializer expected serialization options of type DictionarySerializationOptions, not DocumentSerializationOptions
我用谷歌搜索了它,但找不到任何有用的東西.我做錯了什么?
I googled it, but couldn't find anything useful. What am I doing wrong?
推薦答案
驅動需要能夠找到_id字段.您可以創建一個只有兩個屬性的 C# 類:Id 和 Values.
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; }
}
請注意,我們必須使用 Dictionary<string, object>而不是哈希表.
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);
我們可以使用 MongoDB shell 來確認插入的文檔是否具有所需的形式:
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")
}
>
這篇關于使用 c# 驅動程序將字典插入 MongoDB的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!