2016-08-18 114 views
0

這是我從MongoDB遷移到常規MongoDB集合後的Mongo文檔。將二進制文件數據從SQL Server遷移到MongoDB GridFS

{ 
"TicketId": 23, 
"Attachments" : [ 
     { 
      "_id" : 4221, 
      "Name" : "profile Pic", 
      "Size" : 218112, 
      "Description" : "User Profile Pic", 
      "Data" :{ "$binary" : "0M8R4KGxGuE.............", 
      "IsPrivate" : false, 
      "AttachmentType" = { 
           "ContentType" = "image/png", 
           "FileExtension" = ".png" 
           }, 
      "CreatedByUserId" : 12, 
      "CreatedDateTimeUtc" : ISODate("2012-05-21T18:40:08.570Z"), 
     }, 
    { // Another attachment }, 
    { // Another attachment }, 
    { // Another attachment }] 
} 

但我有超過16 MB大小的附件,因爲MongoDB文檔大小限制爲16 MB我不能使用這種方法來保存我的附件。

看起來像GridFS是一種在MongoDB中保存文件的正確方法 我在SO https://stackoverflow.com/a/4990536/942855上找到了這個答案,它解釋瞭如何將新文件保存到GridFS。但我需要能夠將數據從SQL Server遷移到MongoGridFS。

此外,當您上傳文件到GRIDFS,它似乎會產生很少的默認字段,我想知道如何添加額外的字段到它映射到其他集合?

或者我應該考慮保持與其他映射集合有關的所有信息附件,並將gridFsInfo.Id數組添加到映射中?

我使用MongoDB的3.2 MongoDB的C#驅動

回答

0

這是我最後只是

連接到MongoGridFs

MongoCredential mongoCredential = MongoCredential.CreateCredential("dbName", "userName", "password"); 
      var mongoServerSettings = new MongoServerSettings {Server = new MongoServerAddress("host Ip",27017), 
       Credentials = new List<MongoCredential> { mongoCredential }, 
       ConnectionMode = ConnectionMode.Automatic, ConnectTimeout = new TimeSpan(0,0,0,30)}; 
      var mongoServer = new MongoServer(mongoServerSettings); 
      var mongoGridFsSettings = new MongoGridFSSettings { }; 
      var MongoGridFs = new MongoGridFS(mongoServer, DatabaseName, mongoGridFsSettings); 

在我的C#SQL到蒙戈出口

ticket.Attachments = (from ta in context.TicketAttachments 
              join a in context.Attachments on ta.AttachmentId equals a.Id 
              join at in context.AttachmentTypes on a.TypeId equals at.Id 
              where ta.TicketId == ticket.Id 
              select new Domain.Model.Tickets.Attachment 
              { 
               Id = a.Id, 
               // Load all fields 
               Data = a.Data, 
               Size = a.Size, 
               Name = a.Name, 
               AttachmentType = new Domain.Model.Tickets.AttachmentType() 
               { 
                ContentType = at.ContentType, 
                FileExtension = at.FileExtension 
               } 
              }).ToList(); 

        foreach (var attachment in ticket.Attachments) 
        { 
         Stream stream = new MemoryStream(attachment.Data); 
         MongoGridFSFileInfo mongoGridFsFileInfo = mongoDbContext.MongoGridFs.Upload(stream, attachment.Name); 
         attachment.GridFsObjectId = mongoGridFsFileInfo.Id.AsObjectId; 
        } 

最後將我的ticket.Attachments對象保存在我的常規MongoCollection中