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.
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/ } );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With