mongodb中$ where查询中两个不同字段的逻辑或 [英] Logical OR for two different fields in $where queries in mongodb

查看:552
本文介绍了mongodb中$ where查询中两个不同字段的逻辑或的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您将如何查询下面的查询,我要在伦敦的酒店还是在名称中有希尔顿的酒店?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆