用于计算mongodb主字符串中子字符串的出现的聚合

我是MongoDB的新手,可能是一个菜鸟问题。

我想计算在MongoDB中使用聚合的消息字段中“ lupoK”重复的次数-“ message”:“ 第一个lupoK lupoK ”,我正在使用studio3t界面。

我的文档结构是-

{ 
    "_id" : ObjectId("5df9c780b05196da93be262b"),"id" : "61a4c53a-aa99-4336-ab4f-07bb7f618889","time" : "00:00:45","username" : "siul","message" : "***first lupoK lupoK***","emoticon_place" : [
        {
            "_id" : "128428","begin" : NumberInt(6),"end" : NumberInt(10)
        }
    ],"fragments" : [
        {
            "text" : "first "
        },{
            "emoticon" : {
                "emoticon_id" : "128428","emoticon_set_id" : ""
            },"text" : "***lupoK***"
        },"text" : "***lupoK***"
        }
    ]
}

提前谢谢!

janwen2010 回答:用于计算mongodb主字符串中子字符串的出现的聚合

这在 mongo shell 中有效(假设message字段是一个字符串并且存在):

db.test.aggregate( [
  { 
      $project: { 
          _id: 0,message: 1,count: { 
              $subtract: [ 
                  { $size: { $split: [ "$message","lupoK" ] } },1 
              ] 
          } 
      } 
  }
] )


注意:

$ split操作基于分隔符分割消息字符串-在这种情况下,分隔符为“ lupoK”。拆分返回由“ lupoK”分隔的令牌数组。因此,令牌的数量减去1,得出使用“ lupoK”的次数,即“ lupoK”的出现次数。

使用以下示例消息字符串检查结果:

"***first lupoK lupoK***"
"lupoKlupoK"
" lupoK lupoK "
""
"lupoKlupoKlupoK"
"lupoK"
"HELLO * lupoK* WORLD"
"HELLO WORLD"
"***first lupoK lupoKlupoK lupoK***lupoK *** last lupoK."

例如,某些字符串的标记:

  • "***first lupoK lupoK***"生成这三个令牌:[ "***first"," ","***" ]
  • "HELLO * lupoK* WORLD"具有以下两个标记:[ "HELLO * ","* WORLD" ]
  • "***first lupoK lupoKlupoK lupoK***lupoK *** last lupoK."有七个令牌:[ "***first ","","***"," ***last ","." ]
本文链接:https://www.f2er.com/2899121.html

大家都在问