For example if I have a Mongoose schema with fields like title and body:
例如,如果我有一个Mongoose模式,其中包含title和body等字段:
var Datum = db.model('Datum', {
title: { type: String },
body: { type: String },
}
Now I want to search both fields for a substring, I can do something like this:
现在我想在两个字段中搜索子字符串,我可以这样做:
Datum.find({
{ $or: [ { title: substring }, { body: substring } ] }
},
function(results) {
console.log(results)
})
but I'd like to give title a bigger weight, so for two entries, if one matched in title
, another matched in body
, I'd like the former to be returned in a higher order.
但是我想给一个更大的权重,所以对于两个条目,如果一个匹配的标题,另一个匹配的身体,我希望前者以更高的顺序返回。
Is there anyway for mongoDB to return which condition matched in each result? Or do I have to search the database multiple times for this purpose?
是否有mongoDB返回每个结果中匹配的条件?或者我是否必须多次搜索数据库才能达到此目的?
2 个解决方案
#1
2
when you create text indexes in MongoDB the default weight assigned to each indexed field is 1. however if you want to give a particular field more weight you can include weights option when you create index and that will do the trick for you.
当您在MongoDB中创建文本索引时,分配给每个索引字段的默认权重为1.但是,如果您希望为特定字段赋予更多权重,则可以在创建索引时包含权重选项,这将为您完成。
{
db.yourCollection.createIndex(
{
title: "text",
body: "text",
},
{
weights: {
title: 10,
body: 5
},
name: "myIndex"
}
)
}
#2
0
afaik there is no function like match rate for non text indexes. (see satish chennupati answer for text index)
afaik没有像非文本索引匹配率的功能。 (请参阅satish chennupati文本索引的答案)
To cover that, mongo response need to be processed client side, to avoid expensive server calls, and depends on document number one check or loop need to be executed.
为了弥补这一点,需要在客户端处理mongo响应,以避免昂贵的服务器调用,并且依赖于需要执行的文档第一个检查或循环。
#1
2
when you create text indexes in MongoDB the default weight assigned to each indexed field is 1. however if you want to give a particular field more weight you can include weights option when you create index and that will do the trick for you.
当您在MongoDB中创建文本索引时,分配给每个索引字段的默认权重为1.但是,如果您希望为特定字段赋予更多权重,则可以在创建索引时包含权重选项,这将为您完成。
{
db.yourCollection.createIndex(
{
title: "text",
body: "text",
},
{
weights: {
title: 10,
body: 5
},
name: "myIndex"
}
)
}
#2
0
afaik there is no function like match rate for non text indexes. (see satish chennupati answer for text index)
afaik没有像非文本索引匹配率的功能。 (请参阅satish chennupati文本索引的答案)
To cover that, mongo response need to be processed client side, to avoid expensive server calls, and depends on document number one check or loop need to be executed.
为了弥补这一点,需要在客户端处理mongo响应,以避免昂贵的服务器调用,并且依赖于需要执行的文档第一个检查或循环。