bapu

bapu

  • 0
  • 13
  • 0

inserting nested document in mongodb using c#

Feb 10 2017 9:58 AM
Hello All,
 
I am new to mongodb and c# and I am trying to insert nested documents in mongoDB using c#, I can insert CompanyName, Address etc, but when it comes to add key contacts I have no idea how to do it, user will enter key contacts into grid view so it might be one or more than one. please see my code below
 
var connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
var server = client.GetServer();
var database = server.GetDatabase("Test2");
var customer = database.GetCollection("Address");
MyCustomers p = new MyCustomers();
p.CustomerName = "Company Name";
p.Address1 = "This is address 1";
p.Address2 = "This is address 2";
p.City = "City Name";
for (int i = 0; i <= gvTest.RowCount - 2; i++)
{
p.KeyContacts = new List<KeyContact>
{
new KeyContact {Title = gvTest["title", i].Value.ToString(),
FirstName = gvTest["firstName", i].Value.ToString(),
LastName = gvTest["lastName", i].Value.ToString(),
Designation = gvTest["designation", i].Value.ToString() }
};
}
var document = new BsonDocument();
document.Add("Com", p.CustomerName);
document.Add("Add1", p.Address1);
document.Add("Add2", p.Address2);
document.Add("City", p.City);
var keyContacts = new BsonArray();
keyContacts.Add(new BsonDocument
{
{I have no idea what to do here}
});
document.Add("KeyContacts", keyContacts);
customer.Insert(document);
///////////////////////
public class KeyContact
{
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Designation { get; set; }
}
//////////////////////
public class MyCustomers
{
//company
private string _customerName;
public string CustomerName
{
get { return _customerName; }
set { _customerName = value; }
}
private string _add1;
public string Address1
{
get { return _add1; }
set { _add1 = value; }
}
private string _add2;
public string Address2
{
get { return _add2; }
set { _add2 = value; }
}
private string _city;
public string City
{
get { return _city; }
set { _city = value; }
}
public List<KeyContact> KeyContacts { get; set; }
}
 
Look forward to your help.
Thank You,

Answers (2)