gpt4 book ai didi

mongodb - 使用 mgo 将 Collection 转换为 Capped

转载 作者:IT王子 更新时间:2023-10-29 01:44:33 33 4
gpt4 key购买 nike

我想使用 gopkg.in/mgo.v2 将 mongo 集合转换为 capped。

我能够从头开始创建一个上限集合 - 如下所示:

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

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

第 1 步 - 获取收藏统计信息:

# 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。获取收藏统计信息

这不是 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 这么长的分 block ):

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]

关于mongodb - 使用 mgo 将 Collection 转换为 Capped,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46794192/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com