英文:
How to call dbHash with RunCommand using MongoDB?
问题
使用Go的MongoDB驱动程序,我想使用RunCommand
执行dbHash
命令。我对应该在RunCommand
中使用的“键”和“值”对感到困惑。需要注意的一点是:我想传入一个特定的集合名称进行哈希,例如在这个示例中表示为collection
。例如,这是我现在的代码:db.RunCommand(context.Background(), bson.D{primitive.E{Key: "dbHash: 1", Value: fmt.Sprintf("collections: %s", collection)}})
。请告诉我如何实现这个。
参考资料:
https://docs.mongodb.com/manual/reference/command/dbHash/
https://docs.mongodb.com/manual/reference/method/db.runCommand/
英文:
Using the MongoDB Driver for Go I would like to execute the dbHash
command using RunCommand
. I am confused with the "Key" and "Value" pairs that I should use for RunCommand
. One thing to note: I would like to pass in a specific collection name to hash, denoted as collection
in this example. For example this is what I have now: db.RunCommand(context.Background(), bson.D{primitive.E{Key: "dbHash: 1", Value: fmt.Sprintf("collections: %s", collection}})
. Please let me know how I should implement this.
References:
https://docs.mongodb.com/manual/reference/command/dbHash/
https://docs.mongodb.com/manual/reference/method/db.runCommand/
答案1
得分: 3
bson.D
表示一个文档,它是由bson.E
表示的属性的有序集合,bson.E
是一个简单的结构,包含属性名称和值:
type E struct {
Key string
Value interface{}
}
命令的每个字段都必须是bson.D
文档中的一个元素。命令中的collections
字段必须是一个数组,在你的情况下,它将包含一个单独的元素。在Go中,你可以使用切片来表示这样的数组。
因此,让我们创建命令文档:
cmd := bson.D{
bson.E{Key: "dbHash", Value: 1},
bson.E{Key: "collections", Value: []string{collection}},
}
注意:你可以省略元素中的bson.E
类型,它可以从bson.D
的类型推断出来:
cmd := bson.D{
{Key: "dbHash", Value: 1},
{Key: "collections", Value: []string{collection}},
}
让我们执行这个命令,并将结果文档保存在bson.M
映射中:
var result bson.M
if err := db.RunCommand(context.Background(), cmd).Decode(&result); err != nil {
log.Printf("RunCommand failed: %v", err)
}
fmt.Println(result)
英文:
bson.D
represents a document, it is an ordered collection of properties represented by bson.E
, which is a simple struct holding the property name and value:
type E struct {
Key string
Value interface{}
}
Each field of the command must be an element inside the bson.D
document. The collections
field in the command must be an array, which in your case will contain a single element. In Go, you may use a slice for such an array.
So let's create the command document:
cmd := bson.D{
bson.E{Key: "dbHash", Value: 1},
bson.E{Key: "collections", Value: []string{collection}},
}
Note: you may omit the bson.E
types from the elements, it is inferred from the type of bson.D
:
cmd := bson.D{
{Key: "dbHash", Value: 1},
{Key: "collections", Value: []string{collection}},
}
Let's execute this command, capturing the result document in a bson.M
map:
var result bson.M
if err := db.RunCommand(context.Background(), cmd).Decode(&result); err != nil {
log.Printf("RunCommand failed: %v", err)
}
fmt.Println(result)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论