Query request filter - MongoDB

This request filter targets specifically requests of type QUERY, and allows you to specify what the query document should look like before your code gets invoked.

Note that modern MongoDB clients tend to use MSG requests to run queries, but QUERY requests are still fairly common.


Parameters

Collection name: optional - the name of the collection being queried. If this is specified, the filter will be executed only if when the query is against that collection.

JSON expression: zero or more JSON expressions specifying what the query document should contain for this filter to fire. If more than one expression is specified (separated by semicolons), then all expressions must evaluate to true for this filter to be executed.


Context

The following variables will always be defined when your JavaScript executes:

  • log : the log object

  • context : contains all the variables you'll commonly use:

    • packet : the packet being filtered, which will always be a QUERY packet

    • result : the result object, used to cancel the current packet if desired

    • filterContext: an object containing variables attached to this filter. Any changes to this object will be visible to all invocations of this filter.

    • connectionContext: an object containing variables attached to the connection. Any changes to this object will be visible to all filters defined on this connection.


Example

If a query request filter is defined with the following JSON expression:

find=stocks; filter.stock_symbol=MSFT

Then a QUERY received from the client with the following query document will cause the execution of the filter.

{
find: "stocks",
filter: {
stock_symbol: "MSFT"
},
limit: 20,
$db: "local"
}

The filter code can then modify the query, for instance:

var body = context.packet.getSection(0).getBodyJson();
body.limit = 50;
body.filter.low = {$gt: 30, $lt: 50};

The code can obviously do anything it wants, including responding with an error, or an empty result, etc...

Technical details

A QUERY request is determined to be against a given collection by looking first at its full collection name, which is typically in the format dbname.$cmd, where dbname is the name of the database. If the database name is specified as part of the collection name parameter, it is checked, and the filter is not run if they don't match.

The query document is then checked for one of the following attributes: count, distinct, mapReduce, find, findAndModify. If the attribute exists, and its value is the name of the collection (if specified in the filter's parameters), then the filter is executed. If the query document does not have one of these attributes, then the filter is not executed.