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

58 views
Skip to first unread message

Bohdan Cherchyk

unread,
Oct 12, 2012, 3:40:21 PM10/12/12
to mongod...@googlegroups.com

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.

Rob Moore

unread,
Oct 12, 2012, 7:08:33 PM10/12/12
to mongod...@googlegroups.com

Have you tried using a regular expression?
   { $match: { "content" : /.*someString.*/ } }

Rob.

Bohdan Cherchyk

unread,
Oct 16, 2012, 10:03:25 AM10/16/12
to mongod...@googlegroups.com
is there something more effective than regular expressions?

Asya Kamsky

unread,
Oct 16, 2012, 2:22:43 PM10/16/12
to mongod...@googlegroups.com
It's not advisable to use $where as it's not very performant (it has to spawn a Javascript process).
There is no other way that I know of that you can search by a substring.

Asya
Reply all
Reply to author
Forward
0 new messages