版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37263637/article/details/82872622
最近在参加mongodb university 课程中遇到了一个题目,在一个商品界面要实现一个搜索,以某个关键词搜索所有商品中标题,描述包含该关键词的商品并返回。
这个问题实质就是查询字段文本中包含某段字符的数据。
数据库中document形式如下:
{ _id: 10,
title: 'Green T-shirt',
slogan: 'MongoDB community shirt',
description:
'Crafted from ultra-soft combed cotton, this essential t-shirt features sporty contrast tipping and MongoDB\'s signature leaf.',
stars: 0,
category: 'Apparel',
img_url: '/img/products/green-tshirt.jpg',
price: 20 }
我们的目的是要在title.slogan,description字段中找到待搜索的关键字。
这里就可以在上面三个字段上建立文本索引:
createIndex({ title : "text" , slogan:"text", description:"text"})
文本索引使用
find({$text:{$search:query}})
Mongo shell 使用sample code:
db.item.createIndex({ title : "text" , slogan:"text", description:"text"})
//创建文本索引
db.item.getIndexes()
//查看索引是否创建成功
//并可以根据getIndex查询出来得的 key删除索引
db.item.dropIndex({_fts:"text", "_ftsx" : 1})
//查找 以leaf为key的数据条目
db.item.find({KaTeX parse error: Expected '}', got 'EOF' at end of input: text:{search:“leaf”}}).toArray()
MongoDB Nodejs driver 版本
database.collection( 'item' ).createIndex(
{ title : "text" , slogan:"text", description:"text"}, function(err, result) {
console.log(result);
// callback(result);
});
database.collection( 'item' ).find({$text:{$search:query}}).toArray((err, result)=>{
console.info(result);
callback(result);
})