How do I create the following开发者_JAVA百科 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:
var document = new BsonDocument {
{ "name", "John Doe" },
{ "classes", new BsonArray {
new BsonDocument("classname", "Class1"),
new BsonDocument("classname", "Class2")
}}
};
var json = document.ToJson();
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.
Suppose you have following classes:
public class NestedClass
{
public string ClassName {get;set;}
}
public class Person
{
public Person()
{
Classes = new List<NestedClass>();
}
[BsonId]
public string PersonId {get;set;}
public string Name {get;set;}
public List<NestedClass> Classes {get;set;}
}
You need:
Create create and initialize instance of class that you want to save
var person = new Person(){PersonId = Guid.NewGuid().ToString(), Name = "Some name"};
person.Classes.Add(new NestedClass(){ ClassName="classname1"})
person.Classes.Add(new NestedClass(){ ClassName="classname2"})
than
var server = MongoServer.Create("mongodb://localhost:27020");
MongoDatabase test = server.GetDatabase("test");
MongoCollection students = test.GetCollection<Person>("students");
students.Insert(person.ToBsonDocument()); // it will automatically serialize and insert person
Also be sure that you have run mongodb.
精彩评论