0

In SQL there exists the syntax:

SELECT
    TemplateID,
    Body
FROM
    #Template
WHERE
    Body LIKE '%[^0-9a-zA-Z ]%'  

Taken from the SQL question here
Where the expression finds rows with Body containing invalid characters (not number or alphabet).

Is there a similarly succinct way to find fields which contain invalid (or special) characters in a MongoDB query?

cryanbhu
  • 4,780
  • 6
  • 29
  • 47

2 Answers2

1

You can try MongoDB $regsx as below:

db.collection.aggregate([
    {
        $match: { 
            $or: [
                {'fieldName': { $regex: "$", $options: 'i' } },
                {'fieldName': { $regex: "#", $options: 'i' } },
                /* Append you special char here in array */
            ]
        }
    }
])
Jitendra
  • 3,135
  • 2
  • 26
  • 42
1

I have found that the regex can be used in Mongo as well as such:

db.myCollection.
find(
  {
    "title": {
                 "$regex": ".*[^0-9a-zA-z |,'-:&%].*"
             }
  })

Or a cleaner and more elegant regex, based on (grep) Regex to match non-ASCII characters?

db.myCollection.find(
{
    'title': {'$regex': ".*[^[:ascii:]].*"}
},
{
    'title': 1,
    '_id': 0
}
).limit(10)
cryanbhu
  • 4,780
  • 6
  • 29
  • 47