Combining $regex and $or operators in Mongo

若如初见. 提交于 2019-12-17 10:05:33

问题


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

db.users.insert([{name: "Alice"}, {name: "Bob"}, {name: "Carol"}, {name: "Dan"}, {name: "Dave"}])

Using $regex works fine:

> db.users.find({name: {$regex: "^Da"}})
{ "_id" : ObjectId("53e33682b09f1ca437078b1d"), "name" : "Dan" }
{ "_id" : ObjectId("53e33682b09f1ca437078b1e"), "name" : "Dave" }

When introducing $or, the response is changed. I expected the same response:

> db.users.find({name: {$regex: {$or: ["^Da"]}}})
{ "_id" : ObjectId("53e33682b09f1ca437078b1a"), "name" : "Alice" }
{ "_id" : ObjectId("53e33682b09f1ca437078b1b"), "name" : "Bob" }
{ "_id" : ObjectId("53e33682b09f1ca437078b1c"), "name" : "Carol" }
{ "_id" : ObjectId("53e33682b09f1ca437078b1d"), "name" : "Dan" }
{ "_id" : ObjectId("53e33682b09f1ca437078b1e"), "name" : "Dave" }

I also tried to change the order of the operators:

> db.users.find({name: {$or: [{$regex: "^Da"}, {$regex: "^Ali"}]}})
error: { "$err" : "invalid operator: $or", "code" : 10068 }

However, it seems that following query works fine, but it's a little bit long (name is repeated):

> db.users.find({$or: [{name: {$regex: "^Da"}}, {name: {$regex: "^Ali"}}]})
{ "_id" : ObjectId("53e33682b09f1ca437078b1a"), "name" : "Alice" }
{ "_id" : ObjectId("53e33682b09f1ca437078b1d"), "name" : "Dan" }
{ "_id" : ObjectId("53e33682b09f1ca437078b1e"), "name" : "Dave" }

Is there any shorter way to use $regex and $or in queries like this?

The goal is to use $regex operator and not /.../ (real regular expressions).


回答1:


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" } })



回答2:


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



来源:https://stackoverflow.com/questions/25177645/combining-regex-and-or-operators-in-mongo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!