Search code examples
javascriptmongodbcomparisonequality

Equivalent of JavaScript non-strict comparisons in MongoDB queries


I'm confident this question must have been asked before but I couldn't find any reference to this topic.

I'm querying a MongoDB collection with the native JavaScript driver using data provided on a URL querystring as input, which therefore does not carry type information and is simply treated as a String.

The problem is, the data I'm trying to match against this input can be of a different type in the collection, for example a Number but I cannot predict this in advance. As far as I can see Mongo default comparison operators operate with strict semantics, so this query:

collection.find({ fieldName: value })

is equivalent to this JavaScript code:

fieldName === value

whereas I would like to apply non-strict semantics in this scenario (==), so that a value of "123" will match both "123" and 123.

Does anyone know if this is possible without compromising the performance of the query?


Solution

  • The problem is, the data I'm trying to match against this input can be of a different type in the collection, for example a Number but I cannot predict this in advance.

    If you can't normalise your values to a consistent type, you could always use the $in operator to find alternatives, eg:

    db.test.find({ fieldName: { $in: [123, "123"]}})
    

    An index on fieldName will include both numeric and string values.

    One caveat to be aware of with mixed types is that sorting by that field may not work as you expect. Numbers and strings have different Lexicographical Order, eg:

    > db.test.find({}, {_id: 0, fieldName:1}).sort({fieldName:1})
    { "fieldName" : 123 }
    { "fieldName" : 456 }
    { "fieldName" : 1233 }
    { "fieldName" : 4566 }
    { "fieldName" : "123" }
    { "fieldName" : "1233" }
    { "fieldName" : "456" }
    { "fieldName" : "4566" }