MongoDB 计算集合中子字符串的出现次数

MongoDB count occurances of a substring in a collection

您好,我是 MongoDb 初学者。我有一个 IRC 聊天记录数据库。文档结构很简单

{ 
    "_id" : ObjectId("000"), 
    "user" : "username", 
    "message" : "foobar foobar potato idontknow", 
    "time" : NumberLong(1451775601469)
}

我有数千个这样的字符串,我想计算字符串 "foobar" 出现的次数。我用谷歌搜索了这个问题,发现了一些关于聚合的信息。我看起来很复杂,我还没有真正发现这个 "simple" 有任何问题。如果有人指出我要研究的正确方向,我会很高兴,而且我不介意一个示例命令完全按照我想要的方式执行。谢谢。

没有任何 built-in 操作员可以解决您的请求。

您可以试试这个查询,但它的性能很差:

db.chat.find().forEach(function(doc){
    print(doc["user"] + " > " + ((doc["message"].match(/foobar/g) || []).length))
})

如果您可以将 message 字段更改为数组,那么我们可以应用 aggregation...

编辑:

如果您将拆分词数组添加到条目中,我们可以应用聚合

Sample:

{
    "_id" : ObjectId("569bb7040586bcb40f7d2539"),
    "user" : "username",
    "fullmessage" : "foobar foobar potato idontknow",
    "message" : [ 
        "foobar", 
        "foobar", 
        "potato", 
        "idontknow"
    ],
    "time" : NumberLong(1451775601469)
}

Aggregation. We create new entry for each array element, match given word (foobar, in this case) and then count matched result.

db.chat.aggregate([
    {"$unwind" : "$message"},
    {"$match" : {"message" : {"$regex" : "foobar", "$options" : "i"}}},
    {"$group" : {_id:{"_id" : "$_id", "user" : "$user", "time" : "$time", "fullmessage" : "$fullmessage"}, "count" : {$sum:1}}},
    {"$project" : {_id:"$_id._id", "user" : "$_id.user", "time" : "$_id.time", "fullmessage" : "$_id.fullmessage", "count" : "$count"}}
])

Result:

[ 
    {
        "_id" : ObjectId("569bb7040586bcb40f7d2539"),
        "count" : 2,
        "user" : "username",
        "time" : NumberLong(1451775601469),
        "fullmessage" : "foobar foobar potato idontknow"
    }
]