Combining $regex and $or operators in Mongo

后端 未结 2 1364
甜味超标
甜味超标 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" } })
    

提交回复
热议问题