javascriptnode.jsmongodbmongo-c-driver

MongoDB $regex operator don't work NodeJS using mongoc


I have read the MongoDB documentation and there is a "$regex" operator. I'm currently doing a NodeJS binding for a driver written in C++ that use bsonsearch. I use this code in NodeJS :

db.find(bson.serialize({foo: {$regex: new RegExp('.', 'i')}}), function (err, docs) {
  //things
});

It goes through C++ and it get processed by mongoc-matcher. But mongoc-matcher return me an error on this :

Invalid operator "$regex"

So, I searched for alternative and I see this works :

db.find(bson.serialize({foo: {$eq: new RegExp('.', 'i')}}), function (err, docs) {
  //things
});

But I need to deal with the $regex operator for backwards compatibily problems. Anyone have the right syntax ?


Solution

  • oh hi, I am the author of bsonsearch!

    edit- Opened a room to discuss https://chat.stackoverflow.com/rooms/181623/bsonsearch

    edit2: it looks like you're trying to use extended JSON with $regex but encoding to BSON bits. We'll need to pick one or the other and use the appropriate bson_new_from_* on the C side to deserialize it.

    My code doesn't really have anything to do with mongo-c-driver other than using some of their code. It's a separate project intended for client-side document matching.

    Assuming you know that and are not trying to connect bsoncompare to mongodb, you'll need to use mongodb's binary regex format directly in the string if you intend to use it that way.

    bsonsearch regex shcema comes directly from mongodb regex schema (splitting $regex from $options) https://docs.mongodb.com/manual/reference/operator/query/regex/

    This test file has examples https://github.com/bauman/bsonsearch/blob/master/lib/tests/bsoncompare_regex.c

    for your specific case, use this:

    spec = {"foo": {"$regex": ".", "$options": "i"}}
                               ^                ^
    ---------------------------^                ^
    --------------------------------------------^ (case insensitive)
    

    put the utf-8 string you want to use as your regex directly in the $regex key(a dot in your case) and add an $options key with for case insensitivity (with an i for case insensitive)

    You probably know this, but a . simply matches exactly one character, anywhere in a string.

    https://www.debuggex.com/cheatsheet/regex/pcre