【问题标题】:Using SqlBulkCopy with MongoDB将 SqlBulkCopy 与 MongoDB 一起使用
【发布时间】:2012-12-17 07:18:30
【问题描述】:

根据上一个问题,我正在尝试从 MongoDB 数据库中执行 SqlBulkCopy,但出现错误并且找不到我应该具有的列类型:

来自数据源的ObjectId类型的给定值无法转换为指定目标列的nvarchar类型。

我的DataTableDataTypeMongoDB.Bson.ObjectId

Microsoft Sql Server 中承载此值的类型应该是什么

我当前的代码:

string connectionString = GetDestinationConnectionString();
var mongoCollection = GetSourceConnectionString();

var queryFind = Query.And(Query.NotExists("sync"), Query.NotIn("challenge_guid", new List<MongoDB.Bson.BsonValue>() { "87558b59-73ee-4f10-add4-b9031551e395" }));
var sourceData = mongoCollection.Find(queryFind).ToList();

DataTable dt = CollectionHelper.ConvertTo<MongoAnswerDoc>(sourceData);

using (SqlConnection destinationConnection =
            new SqlConnection(connectionString))
{
    destinationConnection.Open();

    // Set up the bulk copy object. 
    // Note that the column positions in the source
    // data reader match the column positions in 
    // the destination table so there is no need to
    // map columns.
    using (SqlBulkCopy bulkCopy =
                new SqlBulkCopy(destinationConnection))
    {
        bulkCopy.DestinationTableName = "JK_RawChallengeAnswers";

        try
        {
            // Write from the source to the destination.
            bulkCopy.WriteToServer(dt);
        }
        catch (Exception ex)
        {
            txtMsg.Text = ex.Message;
        }
        finally
        {
            // Dispose of the DataTable.
            dt.Dispose();
            // close connection
            destinationConnection.Close();
        }
    }
}

【问题讨论】:

    标签: c# sql-server mongodb mongodb-.net-driver


    【解决方案1】:

    来自Mongo spec

    ObjectId 是一个 12 字节的 BSON 类型,构造使用:

    • 一个 4 字节的时间戳,
    • 一个 3 字节的机器标识符,
    • 一个 2 字节的进程 ID,以及
    • 一个 3 字节的计数器。

    所以你需要一个BINARY(12) 类型的列来在 SQL 中映射它。

    无论如何,您的代码在任何重要的传输上都会耗尽内存,使用中间 DataTable 内存副本不是可行的方法。 EnableStreaming 并使用 IDataReader 实时迭代源代码。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 2014-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多