1

I'm using MongoDB driver to retrieve data https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo I was trying to explain() the query but this documentation doesn't mention anything related. How can I use this function with the MongoDB driver? https://docs.mongodb.com/manual/reference/method/cursor.explain/

I want to do something like with Go Driver

db.col.find({filter:1}).explain("executionStats")
3
  • That IS a tag. You have the [go] tag. That tells us what language you're using. Putting it in the title, too, is incorrect. It's noisy. It's ugly. It serves no purpose. This is a long-established site guideline. Commented Feb 25, 2021 at 12:56
  • Hi, try explain() on Mongo Shell. Commented Feb 25, 2021 at 13:00
  • @HanielBaez it works on Mongo Shell but I need to generate reports for slow queries using Go driver
    – Ahmed
    Commented Feb 25, 2021 at 13:00

2 Answers 2

2

I don't see anything in Go driver source that implements explain.

However, you can send the explain command yourself using the generic command helper (equivalent of https://docs.mongodb.com/ruby-driver/master/tutorials/ruby-driver-database-tasks/#arbitrary-comands). See https://docs.mongodb.com/manual/reference/command/explain/ for the explain command syntax. You would need to manually construct the find command from the find query you normally use, easiest way to do this is to use command monitoring to see what commands are being sent.

2

you can use RunCmd, for example

func ExampleDatabase_RunCommand() {
    var db *mongo.Database

    // Run an explain command to see the query plan for when a "find" is
    // executed on collection "bar" specify the ReadPreference option to
    // explicitly set the read preference to primary.
    findCmd := bson.D{{"find", "bar"}}
    command := bson.D{{"explain", findCmd}}
    opts := options.RunCmd().SetReadPreference(readpref.Primary())
    var result bson.M
    err := db.RunCommand(context.TODO(), command, opts).Decode(&result)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(result)
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.