当然,对此有多种解决方案。假设您想要执行 OR 查询(即返回查询词匹配 author OR title OR ISBN 的结果),您可以使用正确的索引和 the $or 运算符来执行此操作。
我可能会从一个集合开始,将这些字段中的每一个分开:
{
"_id" : 7,
"title" : "coffee and cream",
"author" : "John Doe",
"isbn" : 12312318
}
db.articles.createIndex( { author : 1 } )
db.articles.createIndex( { isbn : 1 } )
db.articles.createIndex( { title: "text" } )
您需要在每个字段上添加索引...看看text 索引类型和$text queries 这对title 字段很有帮助(注意,您只能每个集合使用 一个 $text 索引)。还请阅读 indexes work with $regex queries 如何对查询 author 有用。
当您获得查询词时,只需查询所有字段。然后,$or 查询将返回与这些字段中的任何一个匹配的结果
获取example in the $text documentation 并针对此解决方案对其进行修改...假设以下记录:
{ "_id" : 1, "subject" : "coffee", "author" : "xyz", "views" : 50, "isbn" : 12312312 }
{ "_id" : 2, "subject" : "Coffee Shopping", "author" : "efg", "views" : 5, "isbn" : 12312313 }
{ "_id" : 3, "subject" : "Baking a cake", "author" : "abc", "views" : 90, "isbn" : 12312314 }
{ "_id" : 4, "subject" : "baking", "author" : "xyz", "views" : 100, "isbn" : 12312315 }
{ "_id" : 5, "subject" : "Café Con Leche", "author" : "abc", "views" : 200, "isbn" : 12312316 }
{ "_id" : 6, "subject" : "Сырники", "author" : "jkl", "views" : 80, "isbn" : 12312317 }
{ "_id" : 7, "subject" : "coffee and cream", "author" : "efg", "views" : 10, "isbn" : 12312318 }
{ "_id" : 8, "subject" : "Cafe con Leche", "author" : "xyz", "views" : 10, "isbn" : 12312319 }
{ "_id" : 10, "subject" : "The Coffee Book: Anatomy of an Industry from Crop to the Last Drop", "author" : "Nina Luttinger", "isbn" : 1595580603 }
搜索作者:
> db.articles.find({ $or: [
{ $text: { $search: "lutt" } },
{ isbn: 'lutt' },
{ author: /lutt/i }
] } )
{ "_id" : 10, "subject" : "The Coffee Book: Anatomy of an Industry from Crop to the Last Drop", "author" : "Nina Luttinger", "isbn" : 1595580603 }
搜索标题:
> db.articles.find({ $or: [
{ $text: { $search: "cafe" } },
{ isbn: 'cafe' },
{ author: /cafe/i }
] } )
{ "_id" : 5, "subject" : "Café Con Leche", "author" : "abc", "views" : 200, "isbn" : 12312316 }
{ "_id" : 8, "subject" : "Cafe con Leche", "author" : "xyz", "views" : 10, "isbn" : 12312319 }
您还可以在服务器端执行一些基本逻辑来检查查询词是否为整数,然后从搜索中删除 isbn 查询运算符或查询 only isbn if查询是一个整数。这意味着上述查询将根本不包含$or 查询列表中的isbn 字段。