0

I have data like this in DB and can not change the value at all `

{
    "_id" : ObjectId("63932a20be6f9527c79432d0"),
    "userId" : "123456789",
    "message" : "{\"badge\":\"10\",\"timeToLive\":86400.0,\"message\":\"Your full speed Internet has 200 MB remaining\",\"eventName\":\"default\",\"sender\":\"SRFC-DataPolicy\",\"contentDetail\":{\"actionLink\":\"http://www.ais.co.th/push-notify_aisapp/before_used_up_post_unlimit.html?mb=300 MB \",\"inboxFlag\":true},\"dataMessage\":{\"displaySize\":{\"unit\":\"percent\",\"height\":95.0,\"width\":95.0},\"mediaDataList\":[{\"mediaNo\":1.0,\"mediaType\":\"webview\",\"mediaExtension\":\"html\",\"mediaUrl\":\"http://www.ais.co.th/push-notify_aisapp/before_used_up_post_unlimit.html?mb=300 MB \"}]}}",
    "createdDate" : ISODate("2022-11-01T11:00:02.526+0000"),
    "updatedDate" : ISODate("2022-11-01T11:00:02.526+0000")
}

` I want to query using regex for mediaUrl in key message

This is my current query

db.getCollection("MyCollection").find({message:{$regex: '300 MB'}})

But if some data have message '300 MB' It will show up, I just want it to show only '300 MB' in mediaUrl in key message

H BEAT
  • 3
  • 5

1 Answers1

0

This should work

db.getCollection("MyCollection").find({message:{$regex: 'mediaUrl.*?300 MB'}})

The dot (.) means any character and the asterisk (*) means any number of times (including 0). The question mark (?) makes it non-greedy. So it matches the text mediaUrl followed by any number of characters and stops when it finds 300 MB.

I highly recommend something like: https://regex101.com/ to try out regex and learn.

Matthias
  • 3,160
  • 2
  • 24
  • 38
  • It worked on mediaUrl but when I need to query 'message' 300 MB in message key, 300 MB in mediaUrl show up too. – H BEAT Dec 16 '22 at 02:59
  • there is no 300 MB in message, it is 200 MB. If you do `message.*200 MB` you get what I think you want.. however, I edited the answer to be `.*?` which should catch the least amount of text possible while still matching, that should also help – Matthias Dec 16 '22 at 09:41