0

I have a collection that contains a list field. The list field contains URLs. I want to search that field and pull out all documents where that pattern appears in at least one element in the list. This is one of my first attempts.

query = collection.find({
'third_party_urls' : {'$in' : ['/.woff/']}
})

This returns zero documents, but I know the condition is true in many cases. MongoDB's documentation states that I can't use the $regex operator in a list, but I can use js object regex. According to MongoDB and a quick google search about js regex, I write a pattern encapsulated in / /. So I am confident that I'm using js regex correctly, but no luck. Any ideas?

1
  • MongoDB implicitly performs array element matches, you do not need $in for that and $in in MQL has different meaning from SQL IN. Commented Jun 26, 2020 at 21:38

1 Answer 1

2

Say we have a collection named so. We insert several documents using following commands in mongo shell:

db.so.insert({urls: ["apple", "banana"]})
db.so.insert({urls: ["apple2", "banana2"]})
db.so.insert({urls: ["apple3", "banana3", "cherry"]})
db.so.insert({urls: ["mongo"]})

Then we can find all documents that has at least one element that begins with apple by issuing:

db.so.find({urls: /^apple.*/})

OR

db.so.find({urls: {$regex: "^apple.*"}})

The result is something like below:

{ "_id" : ObjectId("5ef6829b25a20c5a694d8522"), "urls" : [ "apple", "banana" ] }
{ "_id" : ObjectId("5ef682a525a20c5a694d8523"), "urls" : [ "apple2", "banana2" ] }
{ "_id" : ObjectId("5ef682d425a20c5a694d8524"), "urls" : [ "apple3", "banana3", "cherry" ] }
Sign up to request clarification or add additional context in comments.

1 Comment

The $regex answer worked, the other didn't. Interesting, because Mongo says you can't use the $regex operator inside a list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.