如何在MongoDB中编写一个适用于查找和聚合函数的fieldValue.contains("someString")查询

Che*_*ven 2 mongodb

我需要在MongoDB查询中实现fieldValue.contains("someString")搜索?

我发现的解决方案是

db.main.find(  { $where: "this.content.indexOf('someString') != -1" } );
Run Code Online (Sandbox Code Playgroud)

它适用于查找功能.

但是当我在聚合函数中做同样的事情时

db.foo.aggregate(
    {
        $match: 
                { $where: "this.content.indexOf('someString') != -1" }
    },
    {
        $project :
                {
                    _id : 1,
                    words : 1
                }
    },
    {
        $unwind : "$words"
    },
    {
        $group : {
                    _id : { tags : "$words" },
                    count : { $sum : 1 }
                }
    },
    {
        $sort: {count:-1}
    },
    {
        $limit : 5
    }
);
Run Code Online (Sandbox Code Playgroud)

我有这个结果:

{
        "errmsg" : "exception: $where is not allowed inside of a $match aggregation expression",
        "code" : 16395,
        "ok" : 0
}
Run Code Online (Sandbox Code Playgroud)

问题:如何在MongoDB中编写一个适用于查找和聚合函数的fieldValue.contains("someString")查询.

Joh*_*yHK 8

您可以使用正则表达式:

$match: { content: /someString/ }
Run Code Online (Sandbox Code Playgroud)

您应该使用正则表达式,而不是$where针对find情况下,也因为它的效率更高.

db.main.find( { content: /someString/ } );
Run Code Online (Sandbox Code Playgroud)

  • @Cherven` $ where`肯定效率低下; 请参阅[文档中的大警告](http://docs.mongodb.org/manual/reference/operators/#_S_where).常规快递是此用例的最有效解决方案. (2认同)