JavaScript request filter - MongoDB

The JavaScript request filter is the most flexible of all request filters for MongoDB. It can potentially be called for any packet type, and can modify traffic in any way it sees fit.

Parameters

  • Packet types : optional. If specified, a comma-separated list of packet types for which this filter should be called, for instance: MSG,QUERY,INSERT. Spaces are ignored.

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. This will be one of the MongoDB request packet types.

    • 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

Assume we have an application that issues queries using MSG requests, with the following query:

{
find: "stocks",
filter: {
stock_symbol: "MSFT",
},
limit: 20,
maxTimeMS: 5000,
returnKey: false,
showRecordId: false,
$db: "local"
}

We could decide to restrict this query to only 5 documents, and to modify the query so that the final query document looks like:

{
find: "stocks",
filter: {
stock_symbol: "MSFT",
low: {$gt: 30}
},
limit: 5,
maxTimeMS: 5000,
returnKey: false,
showRecordId: false,
$db: "local"
}

This is done using a request filter for packets of type MSG, with the following code:

var body = context.packet.getSection(0).getBodyJson();
if (body.find && body.find === "stocks" && body.filter.stock_symbol === "MSFT") {
body.limit = 5;
body.filter.low = {$gt: 30};
}