普通网友 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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?