我有一种情况,我希望根据某些单词的出现次数,从定义我自己的函数的mongodb中对我的数据进行排序。
例如,我有这个架构:
const RecipeSchema = mongoose.Schema({
Title: { type: String },
Content: { type: String },
PublishDate: { type: Date },
});
和那些值:
Title: 'Chocolate Cake',
Title: 'Naked Cake',
Title: 'Fruit Cake',
Title: 'Beef'
所以,当我查询"裸蛋糕"时,我喜欢这样的结果
Title: 'Naked Cake', // 1, because have the two words
Title: 'Chocolate Cake', // 2 because have just one word
Title: 'Fruit Cake', // 3 because have just one word
// beef has no match word
今天我有这个查询功能:
Recipe
.find()
.where({ Title: GetQueryExpression(value)})
.sort({ PublishDate: -1 })
.exec(callback);
GetQueryExpression函数是:
function GetQueryExpression(value){
var terms = value.split(' ');
var regexString = "";
for (var i = 0; i < terms.length; i++)
regexString += terms[i] + '|';
regexString = regexString.substr(0, regexString.length - 2);
var result = new RegExp(regexString, 'ig');
return result;
}
有人知道如何实现这种目标,哄骗发生的话!?
答案 0 :(得分:2)
使用Text Search执行不区分大小写的文本搜索,它使用tokenizer&amp;词干算法有效地查找文本。您必须定义text
索引,并在集合的text
索引上执行搜索:
var mongoose = require('mongoose');
var db = mongoose.createConnection("mongodb://localhost:27017/testDB");
var RecipeSchema = mongoose.Schema({
Title: { type: String },
Content: { type: String },
PublishDate: { type: Date },
});
RecipeSchema.index({ name: 'text', 'Title': 'text' });
var Recipe = db.model('Recipe', RecipeSchema);
Recipe.find({ $text: { $search: "naked cake" } }, function(err, res) {
console.log(res);
});