【问题标题】:C# MongoDB driver insert nested pairC# MongoDB 驱动程序插入嵌套对
【发布时间】:2017-05-09 11:02:21
【问题描述】:

我可以将以下 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"
}

如有任何帮助,我们将不胜感激。

【问题讨论】:

  • “我想像这样插入一个嵌套的键/值对:”——根据在线测试人员的说法,这不是有效的 JSON。如果你提供了一个有效的 JSON 以及你想要的正确嵌套,那么我们可以弄清楚如何在 c# 中做同样的事情。有关 JSON 中嵌套对象和数组值的示例,请参阅 here
  • 我编辑了 JSON,使其现在有效。

标签: c# mongodb


【解决方案1】:

您的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));

打印:

{“Key1”:{“subKey1”:“subValue1”},“Key2”:“Value2”,“Key3”:“Value3”}

【讨论】:

    【解决方案2】:

    你必须像那样使用 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"
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-20
      • 2017-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-03
      • 2022-11-20
      相关资源
      最近更新 更多