简体   繁体   中英

C# MongoDB driver insert nested pair

I am able to insert the following JSON into mongodb as such:

{ 
   "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]);
}

I would like to insert a nested key/value pair as such:

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

Any help would be appriciated.

Your values array is likely not setup for the nesting I assume. Here is how I created your example document:

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

Prints:

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

You have to use BsonDocument object like that

 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();
        }

Output

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM