【问题标题】:How to limit string field by words not characters in Aggregation?如何通过聚合中的单词而不是字符来限制字符串字段?
【发布时间】:2022-12-06 16:53:20
【问题描述】:

我的文档看起来像这样:

{
   "_id" : ObjectId("5e41877df4cebbeaebec5146"),
   "Paragraph" : "My Name is John Smith.I am learning MongoDB database"
}
{
   "_id" : ObjectId("5e4187d7f4cebbeaebec5147"),
   "Paragraph" : "David Miller is a good student and learning Spring and Hibernate Framework."
}

我想将段落字段文本限制为 5 个字,如下所示:

{
   "_id" : ObjectId("5e41877df4cebbeaebec5146"),
   "Paragraph" : "My Name is John Smith."
}
{
   "_id" : ObjectId("5e4187d7f4cebbeaebec5147"),
   "Paragraph" : "David Miller is a good"
}

【问题讨论】:

  • 你的意思是作为聚合匹配还是在创建中?很想得到一些代码参考和尝试
  • @EldarB。聚合
  • @EldarB。我正在使用 Paragraph: { $substr: [ "$Paragraph", 0, 10] } 但它使用的是字符而不是单词。

标签: mongodb aggregation-framework


【解决方案1】:

一种选择是使用$split$slice$reduce

db.collection.aggregate([
  {$set: {
      Paragraph: {$reduce: {
          input: {$slice: [{$split: ["$Paragraph", " "]}, 5]},
          initialValue: "",
          in: {$concat: ["$$value", {$concat: ["$$this", " "]}]}
      }}
  }},
  {$set: {
      Paragraph: {
        $substr: ["$Paragraph", 0, {$subtract: [{$strLenCP: "$Paragraph"}, 1]}]
      }
  }}
])

查看它在playground example 上的工作原理

【讨论】:

  • 必须使用适当的间距,它才会起作用。谢谢
  • 更新了答案
  • 通过间距,我的意思是在段落“我的名字是 John Smith。我正在学习 MongoDB 数据库”中,当前结果是“我的名字是 John Smith。我”有 5 个单词。我必须修复段落的间距。它在适当的段落间距下工作正常。
猜你喜欢
  • 2022-12-12
  • 1970-01-01
  • 2012-09-07
  • 1970-01-01
  • 1970-01-01
  • 2021-02-15
  • 2010-12-12
  • 2019-02-13
  • 1970-01-01
相关资源
最近更新 更多