I am trying to insert nested documents into MongoDB using C #. I have a collection called categories. This collection should contain documents with 2 arrays, one of the named categories and one named standard. Inside these arrays, new documents must exist with their identifier, which also contain arrays with the same names as above. Below is what I have so far, but I'm not sure how to proceed. If you look at the code, what I want to do is add the “namingConventions” document nested in the categories array in the categories document, however the naming names must also have a unique identifier.
At this moment, I’m not sure that I did all this in the best way, therefore I am open to all and any advice on all this.
namespace ClassLibrary1
{
using MongoDB.Bson;
using MongoDB.Driver;
public class Class1
{
public void test()
{
string connectionString = "mongodb://localhost";
MongoServer server = MongoServer.Create(connectionString);
MongoDatabase standards = server.GetDatabase("Standards");
MongoCollection<BsonDocument> categories = standards.GetCollection<BsonDocument>("catagories");
BsonDocument[] batch = {
new BsonDocument { { "categories", new BsonArray {} },
{ "standards", new BsonArray { } } },
new BsonDocument { { "catagories", new BsonArray { } },
{ "standards", new BsonArray { } } },
};
categories.InsertBatch(batch);
((BsonArray)batch[0]["categories"]).Add(batch[1]);
categories.Save(batch[0]);
}
}
}
For clarity, this is what I need:
What I am doing is creating a coding standards site. The company wants all standards to be stored in MongoDB in a tree. Everything must have a unique identifier so that, in addition to being requested as a tree, it can also be requested by itself. An example would be:
{
"_id" : ObjectId("4fb39795b74861183c713807"),
"catagories" : [],
"standards" : []
}
{
"_id" : ObjectId("4fb39795b74861183c713806"),
"categories" : [{
"_id" : ObjectId("4fb39795b74861183c713807"),
"catagories" : [],
"standards" : []
}],
"standards" : []
}
, , , "0" "1", , . , , , "0", , , , , . , , .