Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs 菜单
Docs 主页
/
数据库手册
/ / /

$score(聚合)

8.2版本新增

$score

$score 计算并返回一个新分数作为元数据。它还可以选择将输入分数标准化,默认为 0 到 1 之间的范围。

该阶段采用以下语法:

{
$score: {
score: <expression>,
normalization: "none|sigmoid|minMaxScaler",
weight: <expression>
}
}

$score 采用以下字段:

字段
类型
说明

score

表达式(expression)

根据输入分数计算新值并将该值存储在$meta 关键字searchScore 中。所有其他分数都存储在$meta 关键字searchScoreDetails 中。为非数字输入返回错误。

normalization

字符串

可选。将分数标准化为 01 的范围。值可以是:

  • none - 不正常化。

  • sigmoid — 应用以下$sigmoid 表达式:

    1 / (1 + e^-x)

    这里,x 是要标准化的分数。

    如果省略,则默认值为 none

  • minMaxScaler -应用$minMaxScaler 窗口函数:

    (s - min_s) / (max_s - min_s)

    其中:

    • s 是分数。

    • min_s 是最低分数。

    • max_s 是最高分数。

weight

double

可选。规范化后与 score表达式相乘的数字。

$score的输出文档与输入文档相同,但还包括作为元数据的附加计算分数。

如果您在管道中指定多个$score 阶段,管道中的最后一个$score 阶段将覆盖之前$score 阶段的分数元数据。

考虑名为 articles 的集合中的以下文档:

{ "_id" : ObjectId("512bc95fe835e68f199c8686"), "author" : "dave", "score" : 80, "views" : 100 },
{ "_id" : ObjectId("512bc962e835e68f199c8687"), "author" : "dave", "score" : 85, "views" : 521 }
{ "_id" : ObjectId("55f5a192d4bede9ac365b257"), "author" : "ahn", "score" : 60, "views" : 1000 }
{ "_id" : ObjectId("55f5a192d4bede9ac365b258"), "author" : "li", "score" : 55, "views" : 5000 }
{ "_id" : ObjectId("55f5a1d3d4bede9ac365b259"), "author" : "annT", "score" : 60, "views" : 50 }
{ "_id" : ObjectId("55f5a1d3d4bede9ac365b25a"), "author" : "li", "score" : 94, "views" : 999 }
{ "_id" : ObjectId("55f5a1d3d4bede9ac365b25b"), "author" : "ty", "score" : 95, "views" : 1000 }

以下查询使用:

  • $match阶段,用于过滤views 字段值大于或等于1000 的文档。

  • $score阶段来计算新分数,该分数使用$sigmoid 表达式进行归一化,然后乘以指定的权重1

db.articles.aggregate([
{
$match: {
views: { $gte: 1000 }
}
},
{
$score: {
score: "$score",
normalization: "sigmoid",
weight: 1
}
},
{
"$project": {
"_id": 0,
"author": 1,
"views": 1,
"score": 1,
"calculatedScore": { $meta: "score" }
}
}
])
[
{ author: 'ahn', score: 60, views: 1000, calculatedScore: 1 },
{ author: 'li', score: 55, views: 5000, calculatedScore: 1 },
{ author: 'ty', score: 95, views: 1000, calculatedScore: 1 }
]

后退

$sample

在此页面上