How to intercept and log mongodb queries?

2.6k Views Asked by At

How do I get the exact query sent from gmongo driver to mongod (for debugging purposes).

In mysql it is achieved by adding logSql = true to datasource.

I am writing an aggregate query with a matching pipeline between a start and end date. The dates are given as normal java Date classes.

db.collection.aggregate(
            [
                $match:
                    [
                        dateIssued: [

                            $gte: fromDate,

                            $lte: toDate
                        ]
                    ]
            ], 
            [
                $group:
                    [
                        _id: "\$type", 
                        total: 
                            [
                                $sum: 1
                            ]
                    ]
            ])

And it doesn't seem to filter the results based on the date. It's giving me back everything.

2

There are 2 best solutions below

1
On

There is no way to do this from the driver, I found the best way to do it is use mongosniff. See http://docs.mongodb.org/manual/reference/program/mongosniff/

0
On

How do I get the exact query sent from gmongo driver to mongod (for debugging purposes)?

Turn on mongodb profiling and you can log all your queries.

In mysql it is achieved by adding logSql = true to datasource.

I think you want this to automatically happen based on your configuration in Grails. Then, do the following:

In Config.groovy:

mongo.profiling.enabled = true 

In Bootstrap.groovy:

GMongo mongo = new GMongo(grailsApplication.config.grails.mongo.host, grailsApplication.config.grails.mongo.port)
DB db = mongo.getDB(grailsApplication.config.grails.mongo.databaseName)

if( grailsApplication.config.grails.mongo.username ) {
    boolean auth = db.authenticate(grailsApplication.config.grails.mongo.username ,
            grailsApplication.config.grails.mongo.password ? grailsApplication.config.grails.mongo.password.toCharArray() : "" )

    if( !auth ) {
        log.error( "MongoDB failed to authenticate")
        return
    }
}

if( grailsApplication.config.mongo.profiling.enabled ) {
    db.setProfilingLevel(2)

}
else {
    db.setProfilingLevel(0)
}