0

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.

2
  • "I would like to insert a nested key/value pair as such:" -- According to online testers that isn't valid JSON. If you give a valid JSON with the proper nesting you want then we can figure out how to do the same thing in c#. See here for an example of nested objects and array values in JSON. Commented Dec 23, 2016 at 19:00
  • i edited the JSON so that it is now valid. Commented Dec 23, 2016 at 19:09

2 Answers 2

0

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" }

Sign up to request clarification or add additional context in comments.

Comments

0

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"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.