使用 c# 驱动程序将字典插入 MongoDB

时间:2023-03-30
本文介绍了使用 c# 驱动程序将字典插入 MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我无法预测我的 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:有效地将一系列值添加到 ObservableCollection 下一篇:如何按顺序将项目插入列表?

相关文章