我使用MongoDB存储有关咖啡的信息,我遇到了查询问题.
我的文档结构是:
{ _id: "Thailand Bok", tags: ["Strong", "Smooth", "Dark"] }
Run Code Online (Sandbox Code Playgroud)
我正在尝试创建允许我搜索名称或标签的查询.
因此,鉴于查询字符串可能是"Thailand Bok"或["Strong","Smooth"],我想搜索包含_id或每个标记的请求.
如果我用SQL术语思考它可能是这样的:
"WHERE `_id` like 'Not present%' OR ("Strong" IN `tags` AND "Smooth" IN `tags`)"
Run Code Online (Sandbox Code Playgroud)
我到目前为止的查询是:
{
$or: [
{ _id: { $regex: '^Not present', '$options': 'i' } },
{
$and: [
{ tags: 'Strong' },
{ tags: 'Smooth' }
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
编辑:更正查询中的错误,并澄清如果_id匹配或标记匹配,它应该工作
您查询似乎没有问题,除了使用花括号而不是方括号为$或.
{$or: [
{_id: {$regex: '^hailand', $options: 'i'} },
{'$and': [
{tags: 'Strong'},
{tags: 'Smooth'}
]}
]}
Run Code Online (Sandbox Code Playgroud)
工作得很好.
| 归档时间: |
|
| 查看次数: |
5691 次 |
| 最近记录: |