Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write a fieldValue.contains("someString") query in MongoDB that works for find and aggregation functions

Tags:

mongodb

I need to implement fieldValue.contains("someString") search in MongoDB query?

the solution that I found is

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

and it works fine for a find function.

but when I do the same in Aggregation function

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
    }
);

I've got this result:

{
        "errmsg" : "exception: $where is not allowed inside of a $match aggregation expression",
        "code" : 16395,
        "ok" : 0
}

The question: how to write a fieldValue.contains("someString") query in MongoDB that works for find and aggregation functions.

like image 940
Cherven Avatar asked Jan 15 '23 08:01

Cherven


1 Answers

You can use a regular expression for that:

$match: { content: /someString/ }

You should use a regular expression instead of a $where for the find case, too, as it's more efficient.

db.main.find( { content: /someString/ } );
like image 57
JohnnyHK Avatar answered Jan 26 '23 00:01

JohnnyHK