Question

I want to migrate my tables from SQL Server to MongoDB. I use below code and it is working fine:

string strQueryInline = "select * from "+ddl_table.SelectedValue +"";
SqlDataAdapter adpt = new SqlDataAdapter(strQueryInline, con);
DataTable dt = new DataTable();
adpt.Fill(dt);

var collection = db.GetCollection<BsonDocument>(txt_value.Text);

try
{
    foreach (DataRow dr in dt.Rows)
    {
        BsonDocument bson = new BsonDocument();

        for (int i = 0; i < dr.ItemArray.Count(); i++)
        {
            bson.Add(dr.Table.Columns[i].ColumnName, dr[i].ToString());
        }
        collection.Insert(bson);
    }
}

But the problem is that it is taking same name and column name as in SQL Server. But I want to use a different name for the table and some different names for the fields in the mongo collection.. I searched a few links but I am not able to reach the exact solution...

plz suggest something..

Was it helpful?

Solution

I am not sure what you are asking about. Do you mean that you want to have different names for the properties in the mongo documents from the column names in the sql tables?

If this is what you want then I don't know how this could be made automatically. Just add a dictionary that will map the sql column names with the mongo properties names:

// ...
Dictionary<string, string> _mapping = new Dictionay<string, string>();
_mappaing.Add("columnA", "propertyA");
// and so on

// ...

try
{
    foreach (DataRow dr in dt.Rows)
    {
        BsonDocument bson = new BsonDocument();

        for (int i = 0; i < dr.ItemArray.Count(); i++)
        {
            // here use the mapped name instead of the colmn name
            bson.Add(_mapping[dr.Table.Columns[i].ColumnName], dr[i].ToString());
        }
        collection.Insert(bson);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top