2016-02-06 76 views
0

我創建了一個capped集合來存儲我的日誌數據,只有很少的字段。由於某些要求,我想在此集合中添加一個名爲「createAt」的附加字段。在MongoDB中添加一個字段到加蓋集合中

db.myLogs.update({},{$set: {"createAt":new Date()}}) 

這是拋出以下錯誤:

WriteResult({ 
     "nMatched" : 0, 
     "nUpserted" : 0, 
     "nModified" : 0, 
     "writeError" : { 
       "code" : 10003, 
       "errmsg" : "Cannot change the size of a document in a capped collection: 39 != 57" 
     } 
}) 

我如何添加幾場進入封頂收藏?

回答

4

簡單的回答

正如mongod告訴你,你不能。一樣the documentation

If the update operation causes a document to grow beyond the document’s original size, the update operation will fail.

稍微複雜的答案

如果該字段是不是強制性的,只需用字段中添加新的文件,並保留舊的文件,因爲它們是,使用一個合理的默認值沒有該領域的文件。

如果你真的需要做

  1. 停止讀取,並從加蓋收集的文件寫入加蓋收集
  2. 複製到一個臨時收集
  3. 更改文件根據需要在臨時收集
  4. 刪除並重新創建加蓋集合
  5. 按照所需順序從臨時集合中讀取文檔並將它們插入到重新創建的加蓋收藏。

當你做了「1.」之後,你可以使用「2.」這樣的東西。在外殼上:

var bulk = db.temp.initializeOrderedBulkOp(); 
var counter = 0; 

db.capped.find().forEach(

    function(doc){ 
    bulk.insert(doc); 

    // In case you have a lot of documents in 
    // your capped collection, it makes sense 
    // to do an intermediate execute 
    if(++counter % 10000 == 0){ 
     bulk.execute(); 
     bulk = db.temp.initializeOrderedBulkOp(); 
    } 

    } 
); 
// execute the remainder 
bulk.execute() 

這應該很容易適應「5.」

+0

感謝Markus!你解釋得很好。 +1 – Vipul

相關問題