How can I use a regex variable in a query for MongoDB

后端 未结 5 1540
清酒与你
清酒与你 2020-11-30 06:10

I would like to make query MongoDB for documents based on a regex expression that I contruct. For e.g I have constructed a simple regex as follows that is a combination of a

5条回答
  •  迷失自我
    2020-11-30 06:29

    If you want to use the variable val as a parameter of the query part, you can use $regex, for example:

    collection.find({"FirstName": {$regex:val}})
    

    It is not allowed to put $regex in $in operator according to the manual.

    If you want to put regular expression object in $in operator, you have to use JavaScript regular expression object, for example:

    collection.find({"FirstName": {$in: [/abc/, /123/]}})
    

    By the way, val in /val/ is constant string, not the variable as you defined above.

提交回复
热议问题