使用 mgo 将 Collection 转换为 Capped

Convert Collection to Capped with mgo

我想使用 gopkg.in/mgo.v2.

将 mongo collection 转换为上限

我可以从头开始创建上限 collection - 如下所示:

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

我不知道如何获取现有 collection 的统计信息或如何 运行 convertToCapped 命令。

第 1 步 - 获取 Collection 统计数据:

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

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

第 2 步 - 转换为上限

# 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。获取 Collection 统计数据

这不是 mgo 包的一部分,但可以作为可运行的 MongoDB 命令使用:collStats.

运行 collStatsmgo:

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

示例输出(veeeeeeery 这么长的分块):

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

2。转换为上限

您尝试的简单问题是 "size" 参数的值必须是数字而不是 string。引用 convertToCapped 文档:

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>).

正确版本:

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)

示例输出:

Result: map[ok:1]