MongoDB:如何在不指定数组索引的情况下在任何字段的子文档中查找包含字符串的文档?
我想在其任何子文档字段中查找包含单词“school”的所有文档,例如,如果我们有两个文档:MongoDB:如何在不指定数组索引的情况下在任何字段的子文档中查找包含字符串的文档?,mongodb,mongodb-query,Mongodb,Mongodb Query,我想在其任何子文档字段中查找包含单词“school”的所有文档,例如,如果我们有两个文档: { name: "aa", schools: [ { name: "high school", description: "aaaa" }, { name: "a1", description: "blabla bla 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.*/ },
...
]
}
它们是执行此操作的一种方法吗?最简单的方法是创建全文索引 您可以按照以下文档进行操作: 然后可以使用$text运算符查询索引: 在所有字段上创建索引
db.schools.createIndex( { "$**": "text" } )
搜索
db.schools.find({
$text:
{
$search: "school",
$language: "en",
$caseSensitive: false,
$diacriticSensitive: false
}
})
如果您需要一个真正的通配符查询,那么@a-h关于文本索引的答案就是最好的选择。但您也可以通过检查多个字段是否匹配的
$或查询来实现这一点:
db.schools.find({
$or:[
{'schools.name':/school/},
{'schools.description':/school/},
...
]
})
此响应也可以工作,但我认为集合中所有字符串数据的通配符索引太大或没有用处。无论如何谢谢你!