Result set filter - MongoDB

This filter gets (potentially) invoked for every object in a response to a query. More specifically, it is invoked for every object in a cursor in a MSG response packet or a REPLY packet.

Be aware that MongoDB behaves differently across versions. This filter works reliably only with MongoDB version 4.x and above. For older versions of MongoDB, you'll need to use a more generic response filter.


Parameters

Collection name : optional - the full name of a collection (e.g. mydb.mycollection). If specified, the filter will only be invoked if the response is from the specified collection.

JSON expression : optional - a JSON expression. If specified, the filter will be invoked only if at least one of the sections in the packet matches the expression.

Action : can be either Hide or Code. If Hide is selected, then any objects that satisfy the JSON expression will not be returned to the client, and the code (if any) will not be invoked. If Code is selected, the code is invoked.


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 response being filtered. You will usually not deal directly with the packet, which can contain multiple objects, but rather with the row (see below).

    • row : an object being returned to the client after a query of some sort. This object can be modified.

    • matchPath : if the JSON expression parameter is set, then this variable will be set to a list of strings representing the path to the first match in the object. In other words, this points out the reason why this object is being filtered. This is only useful if the JSON expression contains one or more * qualifiers. Note that these are strings, and therefore may need to be converted (typically using parseInt) if they represent numbers.

    • 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

Let's assume that you want to intercept a certain type object that looks like this:

{
"name": "Jane Doe",
"labels": ["python","javascript","perl"],
"address": {
"street": "123 Main St",
"city": "Moose Lake",
"country": "Canada"
}
}

and change it. You can create a message response filter with the following JSON expression:

address.country=Canada;labels[+]=perl

If you wanted to change the address in code:

context.row.address.country = "Utopia";
context.row.address.city = "Eden";