gknauth gknauth - 1 year ago 81
Scala Question

Does MongoDB Scala driver have any equivalent to the explain() function in the JavaScript interface?

Does MongoDB Scala driver have any equivalent to the

function in the JavaScript interface?

I'm wondering what the MongoDB Scala driver does with a query like this:

and(geoWithinBox("geometry", bbox.swLon, bbox.swLat, bbox.neLon, bbox.neLat),
equal("properties.foo", "abc"),

MongoDB does not seem to be using the geospatial index I created and I'm trying to figure out why. Rather, it seems to be scanning every document. At least that's what I noticed when I tried
with this JS query in MongoShell:

{$and: [{"geometry": {$geoWithin: {$box: [ [-78,40],[-76,41] ] }}},
{$and: [{"properties.foo": {$eq: "abc"}},
{"properties.bar": {$exists: 1}}

(I didn't have nested-
s in the first version of the JS immediately above. I was just trying different things to see if they triggered use of the geospatial index.)

Answer Source

This answer is based on current MongoDB Scala driver v1.1.0 and current MongoDB v3.2.

Currently there is no cursor explain() function via the Scala driver. This is because explain has been determined to be not a normal use-case for a driver. I would recommend to use the Mongo Shell for debugging query index usages. See MongoDB driver spec for more info.

However you can still use runCommand to get explain output. For example of $geoWithin query in Mongo Shell :

            $box:[[-78,40], [-76, 41]]

You can do the same using command in Scala like below:

val command = Document("explain" -> Document("find"->"collection", 
                                     "$box"->Seq(Seq(-78, 40), Seq(-76, 41))
val observable = db.runCommand(command).printHeadResult()

Or for aggregation queries

      "aggregate" -> "collection",
      "pipeline" -> List[Document]( ... ),
      "explain" -> true

Worth mentioning that only 2d geospatial index supports $box operator. Make sure that you have the right index for field geometries.

Also, by default queries are constructed implicitly with AND, so you don't have to specify $and explicitly. Your example can be shorten to :

db.collection.find({"geometry": {$geoWithin: {$box: [[-78,40],[-76,41]] }},
                    "properties.foo" : "abc", 
                    "properties.bar": {$exists:true}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download