1

I need a mongodb query something like

db.getCollection("xyz").find({"_id" :  {$regex : {$in : [xxxx/*]}}})

My Use case is -- I have a list of Strings such as

[xyz/12/poi, abc/98/mnb, ytn/65/tdx, ...]

The ids that are there in the collection(test) are something like

xyz/12/poi/2019061304. 

I will get the values like xyz/12/poi from the input list, the other part of the id being yyyymmddhh format.

So, I need to go to the collection and find all the documents matching the input list with the ID of the documents in the test collection.

I can retrieve the documents individually but that does not seem to be a feasible option as the size of the input list is more than 10000.

Can you guys suggest a more feasible solution. Thanks in advance.

I tried using $in with $regex. But it seems mongodb does not support that. I have also tried pattern matching but even that is not feasible for me. Can you please suggest an alternative to using $in with $regex in mongodb.

Expected result could be an aggragate query/a normal query so that we hit the database only once and get the desired output rather than hitting the db for 10000 odd times.

injecteer
  • 20,038
  • 4
  • 45
  • 89
anurag
  • 61
  • 1
  • 2
  • I'm sorry, but I'm not sure I understood you. You want to use $regex with a set of different regex, so you said to use $in, right? – virgiliogm Jun 13 '19 at 11:25
  • I want to use $regex for a list of input. $regex is only for a single element in a json object, but I have a list of input and for each input, I need to use regex. – anurag Jun 13 '19 at 11:32
  • And you couldn't combine the text of the inputs in the same regex? For example, and simplifying it a lot, if in the inputs are the values "a" and "b", the query would be `db.getCollection("xyz").find({"_id" : {$regex: /a|b/}})` – virgiliogm Jun 13 '19 at 11:43
  • Sorry, I just noticed that you want to use `$regex` on `_id` and I don't think that's possible. The `_id` field is not a string, it's an `ObjectId`. – virgiliogm Jun 13 '19 at 11:44
  • https://stackoverflow.com/questions/29568350/query-mongodb-with-a-regex-expression-against-an-objectid – virgiliogm Jun 13 '19 at 11:45
  • In my case, the _id is a String of the format - xyz/123/qwe/yyyymmddhh. I just want to use $regex on a list of Strings(this could be anything). I cannot use pattern matching of mongodb as well. Is there a way we can write an aggregate query for the same ? I am new to MongoDB so it is getting difficult for me to understand. – anurag Jun 13 '19 at 12:11

0 Answers0