Home:ALL Converter>MongoDB $regex with $in clause

MongoDB $regex with $in clause

Ask Time:2019-06-13T19:13:51         Author:anurag

Json Formatter

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.

Author:anurag,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/56579204/mongodb-regex-with-in-clause
yy