Mongodb C# 用数组值保存字典

问题描述 投票:0回答:1

我有一个 mongo 集合:

Fieldset
。如果嵌入对象
Fieldset
有列表
Field

Field
有一个
Dictionary<string, object> Config
我想自由地了解这本词典的价值

public class Fieldset
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

    public string Slug { get; set; }
    [BsonElement("Fields")]
    public List<Field> Fields { get; set; }
}

public class Field
{
    [BsonElement("Config")]
    public Dictionary<string, object> Config { get; set; }
}

这是我想要放入的值的示例。某种键值集合

enter image description here

当我保存时,这就是我在mongo中的值

enter image description here

c# mongodb
1个回答
0
投票

嗯。它像应该的那样工作>

static void Main(string[] args)
{
    var client = new MongoClient();
    var database = client.GetDatabase("SO3");
    var collection = database.GetCollection<Fieldset>("jobject");
    var id = new BsonObjectId(ObjectId.GenerateNewId()).ToString();
    var field =
        new Field
        {
            Config = new Dictionary<string, object> {{"value", "item1key"}, {"lable", "item1value"}}
        };
    var field2 =
        new Field
        {
            Config = new Dictionary<string, object> {{"value", "item2key"}, {"lable", "item2value"}}
        };
    var fieldset = new Fieldset
    {
        Id = id,
        Slug = "aa",
        Fields = new List<Field>
        {
            field,
            field2
        }
    };
    collection.InsertOne(fieldset);
}


{ "_id" : ObjectId("5c55b972ceb9443d385de936"), "Slug" : "aa", "Fields" : [ { "Config" : { "value" : "item1key", "lable" : "item1value" } }, { "Config" : { "value" : "item2key", "lable" : "item2value" } } ] }
© www.soinside.com 2019 - 2024. All rights reserved.