mongodb中$ where查询中两个不同字段的逻辑或 [英] Logical OR for two different fields in $where queries in mongodb
问题描述
您将如何查询下面的查询,我要在伦敦的酒店还是在名称中有希尔顿的酒店?
How do you do a query like the one below, where I want hotels in London OR hotels which have hilton in their name?
此查询 db.hotels.find({$ where:"name =/hilton/i || city =/london/i"})
This query db.hotels.find({$where : "name = /hilton/i || city = /london/i"})
给出了这样的错误 错误:{"$ err":"$ where编译错误"}
gives such an error error: { "$err" : "$where compile error" }
两个查询都可以正常运行: db.hotels.find({$ where:"city =/london/i"}) db.hotels.find({$ where:"name =/hilton/i"})
Both queries separately work ok: db.hotels.find({$where : "city = /london/i"}) db.hotels.find({$where : "name = /hilton/i"})
推荐答案
尝试一下:
db.hotels.find({
$where: "/london/i.test(this.city) || /hilton/i.test(this.hotel)"
})
注意
据我了解,$where
对每个文档进行评估,因此它可能会非常慢.如果您只有一个属性,我建议像这样
NOTE
As far as I understand $where
does a per-document evaluation, so it can be pretty slow. If you'd have a single attribute, I'd suggested smth like
db.hotels.find({name: /(hilton|london)/i})
这篇关于mongodb中$ where查询中两个不同字段的逻辑或的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!