普通网友 2017-10-17 15:49
浏览 34
已采纳

将收藏转换为使用mgo封顶

I would like to convert a mongo collection to capped using gopkg.in/mgo.v2.

I am able to create a capped collection from scratch - as follows:

# Create a Capped Collection
sess.DB("").C("my_collection").Create(&mgo.CollectionInfo{Capped: true, MaxBytes: tenMB, MaxDocs: 10})

I can't work out how to get the stats for an existing collection or how to run convertToCapped command.

Step 1 - Get Collection Stats:

# Mongo
db.getCollection('my_collection').stats();

# mgo // I need to find out how to do this.

Step 2 - Convert to Capped

# Mongo
db.runCommand({"convertToCapped": "my_collection", size: 1000000});

# mgo // I need to find out how to do this.
if err := sess.DB("").Run(bson.D{{"convertToCapped", "my_collection"}, {"size", "1000"}}, nil); err != nil {
        println(err.Error()) // invalid command spec
        os.Exit(1)
}
  • 写回答

1条回答 默认 最新

  • douwei3172 2017-10-17 20:19
    关注

    1. Get Collection Stats

    This is not part of the mgo package, but it is available as a runnable MongoDB command: collStats.

    Running collStats with mgo:

    var doc bson.M
    err := mgr.sess.DB("").Run(bson.D{
        {Name: "collStats", Value: "my_collection"},
    }, &doc)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    
    fmt.Println("Result:", doc)
    fmt.Println("Capped:", doc["capped"])
    // Acquire capped info as a bool value:
    capped, ok := doc["capped"].(bool)
    if ok {
        fmt.Println("Capped bool value:", capped)
    }
    

    Example output (veeeeeeery long so chunked):

    Result: map[ok:1 size:36 storageSize:4096 totalIndexSize:4096  ...chunked...]
    Capped: true
    Capped bool value: true
    

    2. Converting to Capped

    The simple problem with your attempt is that the value of the "size" parameter must be a number and not a string. Quoting from the convertToCapped doc:

    The command has the following syntax:

      { convertToCapped: <collection>, size: <capped size> }
    

    convertToCapped takes an existing collection (<collection>) and transforms it into a capped collection with a maximum size in bytes, specified by the size argument (<capped size>).

    Correct version:

    var doc bson.M
    err := mgr.sess.DB("").Run(bson.D{
        {Name: "convertToCapped", Value: "my_collection"},
        {Name: "size", Value: 1<<20}, // 1 MB
    }, &doc)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    
    fmt.Println("Result:", doc)
    

    Example output:

    Result: map[ok:1]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 三向应力状态求剪应力
  • ¥15 jupyter notebook如何添加libGL.so.1库
  • ¥20 easyPoi能否实现下拉多选或者复选框
  • ¥15 网桥在转发帧时,会变帧的源地址和目的地址吗?
  • ¥15 用Multisim设计汽车尾灯控制电路
  • ¥100 求用matlab求解上述微分方程的程序代码
  • ¥15 MAC安装佳能LBP2900驱动的网盘提取码
  • ¥400 微信停车小程序谁懂的来
  • ¥15 ATAC测序到底用什么peak文件做Diffbind差异分析
  • ¥15 安装ubantu过程中第一个vfat 文件挂载失败