如何使用mongoDb获取字符串中关键字在关键字中的出现次数 [英] How to get the number of occurence of a keyword inside a string using mongoDb

查看:97
本文介绍了如何使用mongoDb获取字符串中关键字在关键字中的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在以下聚合中使用$ search运算符进行文本搜索:但是我想获取匹配关键字的出现次数(不仅是mongo提供的textScore)

I'm doing a text search using the $search operator in the aggregation below : However i'd like to get the number of occurence of the matched keywords (not only the textScore that mongo provides)

  myCollection= await MyCollection.aggregate(
            [
                {
                    $match: {
                        $text: {
                            $search: `${keyword}`
                        }
                    }
                },
                { $sort: { score: { $meta: "textScore" } } },
                {
                    $project: {
                        _id: 1, score: { $meta: "textScore" },
                        // other fields here
                    }
                },
                { $match: { score: { $gt: 1.0 } } },
                { $limit: 100 },
            ],
        )

我的收藏集看起来像这样:(索引仅用于描述)

my collection looks like this: (the index is only for description)

var myCollectionSchema = mongoose.Schema(

    {  name: String,
       email: String
       description: String
    })
    
myCollectionSchema.index({ 'description': 'text' },{ background:true})
    
mongoose.model('myCollection', myCollectionSchema);

那么如何仅使用mongo来实现这样的目标?谢谢

So how to achieve such thing using mongo only ? thanks

推荐答案

尝试一下:

let keyword = new RegExp("Hi", "i")

db.myCollection.aggregate([
    {
        $addFields: {
            num_of_occ: {
                $size: {
                    $filter: {
                        input: { $split: ["$description", " "] },
                        as: "text",
                        cond: {
                            $regexMatch: { input: "$$text", regex: keyword }
                        }
                    }
                }
            }
        }
    }
]);

输出:

[
  {
    "_id" : ObjectId("6033a3b0406aaa04445434a1"),
    "name" : "Dheemanth",
    "description" : "Everything has hI in it.",
    "num_of_occ" : 2
  },
  {
    "_id" : ObjectId("6033a3b0406aaa04445434a2"),
    "name" : "Heath",
    "description" : "shushi ends with Hi.",
    "num_of_occ" : 2
  },
  {
    "_id" : ObjectId("6033a3b0406aaa04445434a3"),
    "name" : "Abdelmlak",
    "description" : "Hi i am Abdelmlak.",
    "num_of_occ" : 1
  },
  {
    "_id" : ObjectId("6033a3b0406aaa04445434a4"),
    "name" : "Alex",
    "description" : "missing keyword",
    "num_of_occ" : 0
  }
]

这篇关于如何使用mongoDb获取字符串中关键字在关键字中的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆