【问题标题】:Add a field into capped collection in MongoDB在 MongoDB 的上限集合中添加一个字段
【发布时间】:2016-05-16 13:33:56
【问题描述】:

我创建了一个上限集合来存储我的日志数据,其中包含几个字段。由于某些要求,我想在此集合中添加一个名为“createAt”的附加字段。

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"
        }
})

如何将一些字段添加到上限集合中?

【问题讨论】:

    标签: mongodb capped-collections


    【解决方案1】:

    简单回答

    正如 mongod 告诉你的那样,你不能。和the documentation一样:

    如果更新操作导致文档超出文档的原始大小,则更新操作将失败。

    稍微复杂的答案

    如果该字段不是强制性的,只需添加带有该字段的新文档并保留旧文档不变,对没有该字段的文档使用合理的默认值。

    如果你真的需要这样做

    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”。

    【讨论】:

    • 谢谢马库斯!!你解释得很好。 +1
    猜你喜欢
    • 2018-12-03
    • 1970-01-01
    • 2015-09-06
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多