Combining $regex and $or operators in Mongo

后端 未结 2 1360
甜味超标
甜味超标 2020-12-02 01:48

I want to use $or and $regex operators same time.

db.users.insert([{name: \"Alice\"}, {name: \"Bob\"}, {name: \"Carol\

相关标签:
2条回答
  • 2020-12-02 02:19

    The $or operator expects whole conditions so the correct form would be:

    db.users.find({ "$or": [
        { "name": { "$regex": "^Da"} }, 
        { "name": { "$regex": "^Ali" }}
    ]})
    

    Or of course using $in:

    db.users.find({ "name": { "$in": [/^Da/,/^Ali/] } })
    

    But it's a regex so you can do:

    db.users.find({ "name": { "$regex": "^Da|^Ali" } })
    
    0 讨论(0)
  • 2020-12-02 02:37

    It is been a while. However, I would add case insensitive to the regex query like the query below. So that, it doesn't matter if names were saved into the database with capital letters:

    db.users.find({ "name": { "$regex": "^Da|^Ali", "$options": "i" } })
    

    Hope it helps

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