Search code examples
mongo-cxx-driver

mongocxx distinct with regex pattern matching


The following working C++ code will return all distinct (unique values) for a given field:

document command;
command.append(
    kvp("distinct", "listings"), 
    kvp("key", "streetName")
);

All distinct values are retrieved and here is an example of the output:

{
    "values": [
        "3rd street",
        "4th",
        "5th",
        ...
        "zion",
        "zuni"
    ],
    "ok": 1.0
}

At the mongodb shell, I am able to use a regular expression to reduce distinct values to those beginning with 'glen':

db.listings.distinct(
    "streetName",
    { "streetName": {"$regex": /^glen/, "$options" : ""} }
)

Matching distinct values are retrieved and here is an example of the output:

[ "glen", "glendale", "glenfield" ]

The problem that I am having is that I cannot figure out how to limit distinct values* to those matching a regex pattern when using the mongo-cxx driver:

document command;
command.append(
    kvp("distinct", "listings"), 
    kvp("key", "streetName"),
    kvp("streetName", bsoncxx::types::b_regex{ "^glen"})
);

This is what the command that is sent to mongoDB server looks like:

{
    "distinct": "listings",
    "key": "streetName",
    "streetName": {
        "$regex": "^glen",
        "$options": ""
    }
}

Unfortunately, the command immediately above returns the error: BAD (BSON field 'distinct.streetName' is an unknown field.: generic server error)

Hopefully someone can help me figure out how to obtain distinct values for a subset of data (matching documents).


Solution

  • If you don't mind to directly call distinct(), would this attempt to translate the MongoDB shell example you provided work for you?

    db["listings"].distinct(
          "streetName",
           make_document(kvp("streetName", bsoncxx::types::b_regex{ "^glen" }))
    );