2016-02-06 75 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

相关问题