1

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..

1
  • I don't understand -- your code does exactly what you programmed it to do? GetCollection({name}). That controls the collection name. Map the column names to new field names in your loop and insert. Commented Jun 5, 2013 at 12:22

1 Answer 1

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.