How do I create the following document using the official c# driver?
{
"name": "John Doe",
"classess": [
{
"classname": "Class1"
}
{
"classname": "Class2"
}
]
}
The below code doesn’t work
string cs = "mongodb://localhost";
MongoServer server = MongoServer.Create(cs);
MongoDatabase test = server.GetDatabase("test");
MongoCollection<BsonDocument> students = test.GetCollection("students");
BsonDocument doc = new BsonDocument();
doc.Add(new BsonElement("name", "John doe"));
//Create the list
List<BsonDocument> classes = new List<BsonDocument>();
classes.Add(new BsonDocument(new BsonElement("classname","Test1")));
classes.Add(new BsonDocument(new BsonElement("classname","Test2")));
the following line will throw an error for obvious reason. What is the proper way of doing this?
doc.Add(new BsonElement("classess",classes));
students.Insert(doc);
Thank you.
To create that document using only BsonDocument classes I would write:
This example is using C#’s collection initializer syntax.
The last line is just for debugging. You can look at the json variable and see if you got the result you wanted.