ck0mpana
ck0mpana

Reputation: 43

How to call dbHash with RunCommand using MongoDB?

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/

Upvotes: 1

Views: 368

Answers (1)

icza
icza

Reputation: 418137

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)

Upvotes: 3

Related Questions