Using $regex with $or

I’m trying to implement a basic people search that will search across three fields to find a match (only one field needs to match). I need to search multiple fields with one regex, and return any records that match.
For example:

var regex = new RegExp('^', stringQuery);
var query = {
    "$or": [
        {
            "_id": {
                "$regex": regex,
            },

            "firstName": {
                "$regex": regex,
            },
        }
    ]
};
db.find(query, function(error, people) {
    // Do something
});

Is this possible? If so, am I using the wrong syntax here or something? Results turn up nothing if stringQuery is ‘bdfoster’ and I have a record with ‘_id’ of ‘bdfoster’.

Thanks for any advice you can throw my way.

1 possible answer(s) on “Using $regex with $or

  1. Thanks. For those interested, this is the proper way:

        person.macros.search = function(searchString, callback) {
    
    
            // Take out spaces and replace with pipes
            searchString = searchString.split(' ').join('|');
    
            // Use searchString to build rest of regex
            // -> Note: 'i' for case insensitive
            var regex = new RegExp(searchString, 'i');
    
            // Build query, using regex for each searchable field
            var query = {
                $or: [
                    {
                        "_id": {
                            "$regex": regex,
                        },
                    },
    
                    {
                        "firstName": {
                            "$regex": regex,
                        },
                    },
    
                    {
                        "lastName": {
                            "$regex": regex,
                        },
                    },
    
                    {
                        "barcode": {
                            "$regex": regex,
                        },
                    },
                ]
            };
    
            // Do not return password for each person
            var projections = {
                "password": 0
            };
    
            db.person.find(query, projections, callback);
        };