How to query a mongoDB object to find if it contain any emoji

Viewed 26

I have a collection that records comments from users. Something like the below: { _id:1 "statusReason" : { "text" : { "value" :"Hello there " } }

} I need to write a query that can identify any comments containing any emoji. Please help. Thanks!

MongoDB version: 3.4.24

2 Answers

As MongoDB stores by default using UTF-8, you can simply search with regex of the unicode range of the emojis that you are interested of. You can check for the latest unicode range for emojis here

db.collection.find({
  "statusReason.text.value": {
    "$regex": "[\\x{0023}-\\x{1FAF8}]"
  }
})

Here is the Mongo playground for your reference.

Using that example:

[
  {
    "key": 1,
    "message": ""
  },
  {
    "key": 2,
    "message": "excellent service"
  }
]

And that query:

db.collection.find({
  message: {
    $in: [
      ""
    ]
  }
})

I returned the message you requested:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "key": 1,
    "message": ""
  }
]

Here you can see the query in Mongo playground: [Link to Mongo Playground] 1

Useful documentation:

Related