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

后端 未结 5 1522
清酒与你
清酒与你 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.

    0 讨论(0)
  • 2020-11-30 06:35

    You need to create a regular expression object from the string using the RegExp constructor as the /.../ syntax is only for use with literals.

    var stream = collection.find({"FirstName": new RegExp(val)}).stream();
    
    0 讨论(0)
  • 2020-11-30 06:35

    I was having same problem with my title and after lots of searching, i found this answer Here,

    var search = 'Joe';
    db.users.find(name: /^search/)
    db.users.find(name: {$regex: /^search/});
    db.users.find(name: {$regex: "/^" + search + "/"});
    

    The queries above won’t return anything. The solution to this little problem is quite simple:

    db.users.find(name: new RegExp(search)) //For substring search, case sensitive. 
    db.users.find(name: new RegExp('^' + search + '$')) //For exact search, case sensitive
    db.users.find(name: new RegExp(search, ‘i')) //For substring search, case insensitive
    db.users.find(name: new RegExp('^' +search + '$', 'i')); //For exact search, case insensitive
    

    Other flags or properties can be added base on reference here

    0 讨论(0)
  • 2020-11-30 06:44

    Use the following code to use dynamic value in regex with or operations

    {$match: { $or: [{ 'title': { $regex:  request.query.val, $options: 'i'} }, { 'skills_required': { $regex:  request.query.val, $options: 'i'} }] }},
    
    0 讨论(0)
  • 2020-11-30 06:44
    let test = `what your regex should 
    search`;
    
    collection.find({
        fieldName: {$regex: test}
    }).then(result => red.send(result));
    

    // tested on mongoose but should work on mongodb too

    0 讨论(0)
提交回复
热议问题