我正在寻找一种方法来携带一些数值(如概率)以及我想在MongoDB的聚合管道中匹配的键,因此我可以使用这些值来计算最终的聚合匹配的条目。我想知道是否有办法用聚合管道实现它。我可以使用$ project语句在提供的字典中查找密钥吗?
示例文件:
{
_id: 'keyword',
matches: [ { doc_id: 'doc_1', score: 0.5 }, { doc_id: 'doc_2', score: 0.5 } ]
}
示例管道:
var doc_weights = { 'doc_1': 0.5, 'doc_2': 0.5 };
var doc_ids = ['doc_1', 'doc_2'];
db.keyword_search.aggregate(
[
// Find keywords whose search results contain our doc_ids
{ '$match': {
'matches.doc_id' : { '$in': doc_ids }
}},
// Unwind the array of matches containing our doc_ids
{ '$unwind': {
'path': '$matches',
}},
// Filter out matches with for irrelevant doc_ids
{ '$match': {
'matches.doc_id' : { '$in': doc_ids }
}},
// Weight each match as a product of the match entry score
// and the document weight
{ '$project': {
'match_weight': { '$multiply': [ '$score', doc_weights['$matches.doc_id'] ] },
}},
// Compute aggregates
{ '$group': {
'_id': '$_id',
'weight': { '$sum': '$weight' },
}},
{ '$limit': 1000 }
]
);