我想在其任何子文档字段中查找包含单词“school”的所有文档,例如,如果我们有两个文档:
{
name: "aa",
schools: [
{
name: "high school",
description: "aaaa"
},
{
name: "a1",
description: "blabla bla school"
},
...
],
},
{
name: "bb",
schools: [
{
name: "bbb",
description: "First school of ..."
},
{
name: "b school",
description: "bbb bb b",
...
}
],
},
这些文件应与第一所或/和第二所学校的名称或/和描述相匹配。
我尝试了这个查询但没有成功:
{
schools: /.*school.*/
}
这也是通过列出字段来实现的:
{
school: [
{ name: /.*school.*/ },
{ description: /.*school.*/ },
...
]
}
他们有办法执行此操作吗?
最佳答案
如果您需要真正的通配符查询,那么 @a-h 关于文本索引的答案就是正确的选择。但您也可以使用 $or
查询来检查多个字段是否匹配:
db.schools.find({
$or: [
{ 'schools.name': /school/ },
{ 'schools.description': /school/ },
...
]
})
关于MongoDB:如何在不指定数组索引的情况下查找任何字段的子文档中包含字符串的文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35557741/