C#MongoDB驱动程序插入嵌套对

时间:2016-12-23 18:52:44

标签: c# mongodb

我能够将以下JSON插入到mongodb中:

{ 
   "Key1" : "Value1", 
   "Key2" :  "Value2", 
   "Key3" : "Value3"
}

//  C# (keys[] and values[] are already populated)
var document = new BsonDocument();

for(int i=0; i<keys.Length; i++)
{
    document.Add(keys[i], values[i]);
}

我想插入一个嵌套的键/值对:

{ 
   "Key1" : { 
       "subKey1" : "subValue1"
    }
   "Key2" :  "Value2", 
   "Key3" : "Value3"
}

任何帮助都会得到满足。

2 个答案:

答案 0 :(得分:0)

我认为您的values数组可能没有为嵌套设置。以下是我创建示例文档的方法:

var doc = new BsonDocument();
doc.Add("Key1", new BsonDocument().Add("subKey1", "subValue1"));
doc.Add("Key2", "Value2");
doc.Add("Key3", "Value3");

Console.WriteLine(MongoDB.Bson.BsonExtensionMethods.ToJson(doc));

打印:

  

{&#34; Key1&#34; :{&#34; subKey1&#34; :&#34; subValue1&#34; },&#34; Key2&#34; :&#34; Value2&#34;,&#34; Key3&#34; :&#34; Value3&#34; }

答案 1 :(得分:0)

您必须使用像这样的BsonDocument对象

 static void Main(string[] args)
        {

            var connectionString = "mongodb://localhost:27017/dbtest?readPreference=primary";
            var mongoUrl = new MongoUrl(connectionString);
            var client = new MongoClient(mongoUrl);
            var database = client.GetDatabase(mongoUrl.DatabaseName);

            var collection = database.GetCollection<BsonDocument>("Documents");

            collection.InsertOne(new BsonDocument("Key1", new BsonDocument("subKey1", "subValue1")));
            collection.InsertOne(new BsonDocument("Key2", "Value2"));
            collection.InsertOne(new BsonDocument("Key3", "Value3"));



            Console.WriteLine(collection.Count(FilterDefinition<BsonDocument>.Empty));
            Console.ReadLine();
        }

输出

/* 1 */
{
    "_id" : ObjectId("586248b4e637f258e88e3bf3"),
    "Key1" : {
        "subKey1" : "subValue1"
    }
}

/* 2 */
{
    "_id" : ObjectId("586248b4e637f258e88e3bf4"),
    "Key2" : "Value2"
}

/* 3 */
{
    "_id" : ObjectId("586248b4e637f258e88e3bf5"),
    "Key3" : "Value3"
}