我需要在MongoDB查询中实现fieldValue.contains("someString")搜索?
我找到的解决方案是
db.main.find( { $where: "this.content.indexOf('someString') != -1" } );
它适用于查找功能。
但是当我在聚合函数中做同样的事情时
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
}
);
我得到了这个结果:
{
"errmsg" : "exception: $where is not allowed inside of a $match aggregation expression",
"code" : 16395,
"ok" : 0
}
问题:如何在MongoDB中编写一个用于查找和聚合函数的fieldValue.contains("someString")查询。
您可以使用正则表达式:
$match: { content: /someString/ }
对于find
情况,您也应该使用正则表达式而不是$where
,因为它更有效。
db.main.find( { content: /someString/ } );