【问题标题】:How to get all the substrings matching given word along with their count in mongodb?如何获取与给定单词匹配的所有子字符串及其在 mongodb 中的计数?
【发布时间】:2017-08-30 10:34:25
【问题描述】:

我在使用 Spring Boot 从 MongoDB 检索数据时遇到以下问题。

这是我的架构:

class Item
{
    @Id
    String _id;
    String description;
}

假设数据库有以下内容:

{"Id1", "carrot vegetable"},
{"Id2", "vegies is a brand"},
{"Id3", "I am Vegetarian"},
{"Id4", "Potato vegetable"},
{"Id5", "Fruits"}

我想要实现的是获取以“veg”开头的术语及其数量。 是这样的:

{"vegetable", 2},
{"vegies", 1},
{"vegetarian", 1}

到目前为止,我遇到了 IndexOfCP 操作,它可以从字符串中找到子字符串。

db.Item.aggregate([ { $match:{ description:/veg/gi } }, { $project:{ index:{ $indexOfCP:[ { $toLower:"$description" }, "veg" ] }, description:1 } }, { $sort:{ index:1 } } ])

但我在结果集中找不到匹配项及其计数。

我如何在 mongo 命令和 spring boot 中做到这一点。

【问题讨论】:

  • 如果是{"Id6", "vegetable isvegetable or vegetables"}的输出应该是什么
  • @shubham 它应该算作 1。O/P 将是:{"vegetable" : 1 } 不是 {"vegetable" : 3}
  • 在这种情况下 ==> {"Id7", "vegetable vegies Vegetarian"} ?
  • @shubham 在这种情况下:{"vegetable" : 1}, {"vegies" : 1}, {"vegetarian" : 1}

标签: regex mongodb spring-boot mongodb-query aggregation-framework


【解决方案1】:
db.Item.aggregate([ 
   { $match:{ description:/veg/gi } },
   { 
     $project :{
        matchedAndUniqWords:{
             $reduce:{
               input:{ $filter:{input:{$split:[{"$toLower":"$description"}," "]},as:"w",cond:{$ne:[{$indexOfCP:["$$w","veg"]},-1]}}},
               initialValue:[],
               in:{
                   $cond:[{$in:["$$this","$$value"]},{$concatArrays:[[],"$$value"]},{$concatArrays:[["$$this"],"$$value"]}]
                  }     
           }
        }
       }
     },
     {
      $unwind:{path : "$matchedAndUniqWords"}
   },
   {
     $group:{_id:"$matchedAndUniqWords",count:{"$sum":1}}
   }]);

【讨论】:

  • 请您解释一下这个查询。
  • 此查询拆分描述,然后仅过滤与您的查询匹配的单词,然后它会减少此结果数组以生成唯一且匹配的单词,正如您所说的,输出应该是 {"Id6", "vegetable is蔬菜或蔬菜"} 为 {"vegetable" : 1 } 然后在展开阶段展开匹配且唯一的关键字数组,然后展开相似词组
  • 这仅适用于 mongodb 3.4 或高于 3.4
  • 非常感谢@shubham 的回答。这正是我所希望的,虽然这需要一些时间才能理解。
猜你喜欢
  • 1970-01-01
  • 2019-10-10
  • 1970-01-01
  • 1970-01-01
  • 2020-10-26
  • 1970-01-01
  • 2020-10-21
  • 2022-11-14
  • 1970-01-01
相关资源
最近更新 更多