2010-12-07 25 views
4

SQLデータベースをmongoDBドキュメントに変換するにはどうすればいいですか?SQLテーブルをmongoDBドキュメントに変換する

私はC#ドライバを使って、テーブルの各行を選択してMongoに保存するループを実装すると思います。しかし、多くのデータを変換するより良い方法を探しています。

+0

(それは良いBSONのlibで)あなたも*たくさんの*を保存するだけでなく、ダンプやエクスポートなど多くのデータ変換の問題を扱うことができるのでより簡単に –

答えて

7

ドライバーの道はFARで最も簡単です。インポート/エクスポートツールは素晴らしいですが、の場合は、のみをペアとして使用しています。テーブルに日付が含まれていて、DBからエクスポートしてmongoにインポートしようとすると、あなたは野生の乗り物のためにいます。

あなたは幸運にも、C#にいます。私たちはルビーを使用しており、私たちがmongoに移行した3200万行のテーブルを持っています。私たちの終わりの解決策は、jsonを出力するpostgresの狂ったSQL文を作ることでした(適切な日付を得るためにいくつかかなりのkludgyを含む)し、コマンドラインの出力をmongoimportにパイプしました。それは書くのに信じられないほどイライラした一日を要した、そして本当に変更することができるもののようなものではありません。

もしあなたがそれを手放すことができたら、m.netドライバでado.netを使用してください。ない場合は、私にはよく

:-)あなたを望む(これは、合計のmongo fanboiから来ていることに注意してください)

+0

他のタイプは、Mongo doesn変換中に好きですか? –

+1

mongoは私たちの本当のキラーでした。なぜなら、mongoはそれが時代から64ビットのダニであると見ており、私たちが使用するものはすべて32ビットの日付を使用しています。私たちはtsvモードでインポートする際に問題がありました。なぜなら、10genによれば、引用された文字列はtsvファイルに改行を入れることができないからです。私たちは他の問題も抱えていましたが、私たちのツール固有のものでした。 –

0

両方ノーム&サムスのC#のmongoドライバは、文書として渡される、厳密に型指定されたクラスをサポートしています。 NhiberbateとLINQ to SQLのクールさを意味します。

私は、SQL Serverからデータを取得するためにLINQ to SQLを使用してc#(クラスを表すクラス)でエンティティを作成し、mongo dbに挿入するために同じ厳密に型指定されたクラスを使用できます。

クラスのいずれかにmongoの識別子(NoRM)属性が含まれていることを確認してください。これは、ドキュメントの一意のIDを生成するためです。

1

私はそれを行うためのツールを作成する必要がありました。 bcp.exeを使用してデータをxmlにエクスポートし、Newtonsoft JSON.NETを使用してjsonに変換してからmongoimportをインポートします。日数はそれ以下でしたが、日付はサポートされていません。

いくつかのコードは非常に汚れた(下記:)

bcp.exeのは次のような構文を使用します。 bcp.exeの「XML RAW( '行')FOR GeoData.dbo.AirportsからSELECT *、ROOT( 'ルート' )、ELEMENTS」queryoutのD:\のTEMP \ tmp1045.tmp -Uxxxx -Pxxxx -Sxxxx -w -r "" -q

JSON:

var r=XmlReader.Create("file://D:/1.xml"); 
    XmlDocument xdoc=new XmlDocument(); 
    xdoc.Load(r); 
    string result=""; 





    //o["Root"]["Airport"]; 
    foreach(XmlNode n in xdoc.ChildNodes[0]){ 
     var rr= JsonConvert.SerializeXmlNode(n);  

     JObject o=JObject.Parse(rr);  

     var co=o.Children().Children().First();  

     foreach (JToken c in co.Children().Where(cc=>cc.Type==JTokenType.Property).ToList()){     
      var prop=c as JProperty;    
      double d; 
      if (double.TryParse(co[prop.Name].Value<string>(),out d)) 
      { 
       co[prop.Name] = d; 
      }   
      //c.Value<string>().Dump(); 
      //c.Value<string>().Dump(); 
      //co[c.Name] 
     } 

     //co["APT_Latitude"].Value<decimal>().Dump();  
     result=result + co.ToString(Newtonsoft.Json.Formatting.None)+"\r\n"; 


    } 
    File.WriteAllText("D:/1.json",result); 

    //result.Dump(); 

mongoimport: D:\のMongoDB \ mongoimport。 exe -c "test" -d "MongoStatic" 1.json> 1

1

Rubyで遊んでいるなら、私はこれを行うのに役立つ宝石を作りました:http://mongify.com/

ソースコードを見つけることができます:https://github.com/anlek/mongify/

本当に簡単で、まっすぐに自分のスキーマを定義し、前方とどのようにそれがMongoDBのに変換する必要があります。埋め込み、テーブル名の変更、フィールド名の変更、その他のオプションを含む

11

これは、私のボックスにあるMongodbにSQLサーバからデータをインポートするために使用しているインポートスクリプトです。 このコードは、MongoDBの(SQL DBに存在する)類似のテーブルを作成するだけです。 カンマ区切りでインポートするテーブルリストを指定することができます。これらのテーブルはすべて問題なくインポートされます。

static void Main(string[] args) 
{ 
    List<string> tablelist = new List<string>(); 
    if (!args[0].Contains(',')) 
     tablelist.Add(args[0]); 
    else 
     tablelist.AddRange(args[0].Split(',')); 
    string sqlconnectionstring = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString(); 
    var connectionString = "mongodb://localhost/?safe=true;w=1;wtimeout=30s"; 
    var safemode = SafeMode.True; 
    MongoServer server = MongoServer.Create(connectionString); 
    MongoDatabase db = server.GetDatabase("testdb"); 
    MongoCollection<MongoDB.Bson.BsonDocument> coll = db.GetCollection<BsonDocument>("test"); 
    //coll.Find().Count(); 
    int i = 0; 
    foreach (string table in tablelist) 
    { 

     using (SqlConnection conn = new SqlConnection(sqlconnectionstring)) 
     { 
      string query = "select * from " + table; 
      using (SqlCommand cmd = new SqlCommand(query, conn)) 
      { 
       /// Delete the MongoDb Collection first to proceed with data insertion 

       if (db.CollectionExists(table)) 
       { 
        MongoCollection<BsonDocument> collection = db.GetCollection<BsonDocument>(table); 
        collection.Drop(); 
       } 
       conn.Open(); 
       SqlDataReader reader = cmd.ExecuteReader(); 
       List<BsonDocument> bsonlist = new List<BsonDocument>(1000); 
       while (reader.Read()) 
       { 
        if (i == 1000) 
        { 
         using (server.RequestStart(db)) 
         { 
          //MongoCollection<MongoDB.Bson.BsonDocument> 
          coll = db.GetCollection<BsonDocument>(table); 
          coll.InsertBatch(bsonlist); 
          bsonlist.RemoveRange(0, bsonlist.Count); 
         } 
         i = 0; 
        } 
        ++i; 
        BsonDocument bson = new BsonDocument(); 
        for (int j = 0; j < reader.FieldCount; j++) 
        { 
         if (reader[j].GetType() == typeof(String)) 
          bson.Add(new BsonElement(reader.GetName(j), reader[j].ToString())); 
         else if ((reader[j].GetType() == typeof(Int32))) 
         { 
          bson.Add(new BsonElement(reader.GetName(j), BsonValue.Create(reader.GetInt32(j)))); 
         } 
         else if (reader[j].GetType() == typeof(Int16)) 
         { 
          bson.Add(new BsonElement(reader.GetName(j), BsonValue.Create(reader.GetInt16(j)))); 
         } 
         else if (reader[j].GetType() == typeof(Int64)) 
         { 
          bson.Add(new BsonElement(reader.GetName(j), BsonValue.Create(reader.GetInt64(j)))); 
         } 
         else if (reader[j].GetType() == typeof(float)) 
         { 
          bson.Add(new BsonElement(reader.GetName(j), BsonValue.Create(reader.GetFloat(j)))); 
         } 
         else if (reader[j].GetType() == typeof(Double)) 
         { 
          bson.Add(new BsonElement(reader.GetName(j), BsonValue.Create(reader.GetDouble(j)))); 
         } 
         else if (reader[j].GetType() == typeof(DateTime)) 
         { 
          bson.Add(new BsonElement(reader.GetName(j), BsonValue.Create(reader.GetDateTime(j)))); 
         } 
         else if (reader[j].GetType() == typeof(Guid)) 
          bson.Add(new BsonElement(reader.GetName(j), BsonValue.Create(reader.GetGuid(j)))); 
         else if (reader[j].GetType() == typeof(Boolean)) 
         { 
          bson.Add(new BsonElement(reader.GetName(j), BsonValue.Create(reader.GetBoolean(j)))); 
         } 
         else if (reader[j].GetType() == typeof(DBNull)) 
         { 
          bson.Add(new BsonElement(reader.GetName(j), BsonNull.Value)); 
         } 
         else if (reader[j].GetType() == typeof(Byte)) 
         { 
          bson.Add(new BsonElement(reader.GetName(j), BsonValue.Create(reader.GetByte(j)))); 
         } 
         else if (reader[j].GetType() == typeof(Byte[])) 
         { 
          bson.Add(new BsonElement(reader.GetName(j), BsonValue.Create(reader[j] as Byte[]))); 
         } 
         else 
          throw new Exception(); 
        } 
        bsonlist.Add(bson); 
       } 
       if (i > 0) 
       { 
        using (server.RequestStart(db)) 
        { 
         //MongoCollection<MongoDB.Bson.BsonDocument> 
         coll = db.GetCollection<BsonDocument>(table); 
         coll.InsertBatch(bsonlist); 
         bsonlist.RemoveRange(0, bsonlist.Count); 
        } 
        i = 0; 
       } 
      } 
     } 
    } 
} 
のMongoDBの哲学は、あなたの最善の策は、C#だけでなく、それはなるために使用している...ので、私は以下のマットに同意するだろう...ドライバ/アプリケーションレベルへのこの種のものの多くをプッシュすることです
+0

MongoServer、MongoDatabaseなどの型を使用するためにどのような参照を追加しなければなりませんか?私はMongoDB.BSON、MongoDB.Driver、MongoDB.Driver.Coreを持っていますが、これらのラインコードはVIsual Studioで赤です。 –

関連する問題