0

I'm using MongoDB as my database engine and trying to execute a find query based on a given keyword. If all of the data fields are type of String, then I could perform the find query like this:

test.find({
    $or: [
        {'field1': {'$regex': req.body.keyword} },
        {'field2': {'$regex': req.body.keyword} }
    ]})
    .then(function(records) {
        if(records.length >= 1) {
            return res.json({error: false, message: null, data: records});
        } else {
            return res.json({error: false, message: "No results", data: null});
        }
    });

However, I have some fields that has a field type of Number and $reqex cannot be used with any other types than String.

Is it even possible to perform a find query on different data types? Any help/ideas/thoughts are much appreciated!

B_CooperA
  • 659
  • 1
  • 9
  • 28
  • Do you mean that in some documents, _field1_ contains a numeric value? Or are you talking about a different field which is always numeric? In that case, can you explain what kind of data you are trying to match? – Vince Bowdren Apr 03 '17 at 12:24

2 Answers2

0

Try using the .toString() method to convert the numbers to strings as you pass them to the $regex operator.

WordBrewery
  • 197
  • 9
0

To answer the more general question first, yes, it's possible to perform a find on different data types, not just strings. $regex is meant for pattern matching on strings though.

Pattern matching on numbers, which seems to be what you are looking for, is demonstrated in this post: MongoDB Regex Search on Integer Value

Here's a specific example that may help... the document is inserted and then it is matched using $where. The result is on the last line:

db.B_CooperA.insert({number:51})
db.B_CooperA.find({ $where: "/^51*/.test(this.number)" })
{ "_id" : ObjectId("58e1e4cfb8400a4eb8032748"), "number" : 51 }
Community
  • 1
  • 1
Joseph Milane
  • 184
  • 1
  • 9