假设我只有一个字段BlogText
。当用户搜索一个单词,如果BlogText
中存在该单词时,我想:
- 在匹配的单词之前仅检索10个单词,在匹配的查询后10个单词,引导并接着省略号。
- 另外,我想由
<b>Matched word</b>
替换Matched word
给定 lorem ipsum只是印刷和排版行业的虚拟文本。自1500年代以来,Lorem Ipsum一直是该行业的标准虚拟文本,当时一台未知的打印机拿起了一个类型的厨房,并将其拼写为制作类型的标本书。它不仅幸存了五个世纪,而且还幸存下来,而且跨越了电子排版,基本上保持不变。它在1960年代通过包含Lorem Ipsum段落的LeTraset板发布,最近在1960年代发布了它,最近在Aldus Pagemaker(包括Lorem Ipsum的版本)等桌面出版软件中发布了它。 我知道这也可以在服务器上完成,但是我想避免检索我不需要的数据(参考第一点)。... has been the industry's standard dummy text ever since the <b>1500<b>s, when an unknown printer took a galley of type and ...
BlogText
中的原始文本是:
您可以使用聚合返回长文本的子字符串。
假设您需要围绕的第一个出现匹配的术语,并且一个空格被用作单词定界符,则管道可以是这样的:
db.collection.aggregate([
{ $match: { BlogText:/1500/ } },
{ $project: {
match: {
$let: {
vars: { pos: { $indexOfCP: [ "$BlogText", "1500" ] }},
in: { $concat: [
{ $reduce: {
input: { $slice: [
{ $split: [
{ $substrCP: [ "$BlogText", 0, "$$pos" ] },
" "
]},
-10
]},
initialValue: "",
in: { $concat : [ "$$value", " ", "$$this" ] }
}},
{ $reduce: {
input: { $slice: [
{ $split: [
{ $substrCP: [ "$BlogText", "$$pos", { $strLenCP: "$BlogText" } ] },
" "
]},
10
]},
initialValue: "",
in: { $concat : [ "$$value", " ", "$$this" ] }
}}
]}
}
}
}}
]);