如何在MongoDB中编写fieldValue.contains(“someString”)查询,该查询适用于查找和聚合函数
我需要在MongoDB查询中实现fieldValue.contains(“someString”)搜索 我找到的解决办法是如何在MongoDB中编写fieldValue.contains(“someString”)查询,该查询适用于查找和聚合函数,mongodb,Mongodb,我需要在MongoDB查询中实现fieldValue.contains(“someString”)搜索 我找到的解决办法是 db.main.find( { $where: "this.content.indexOf('someString') != -1" } ); 对于find函数来说,它工作得很好 但当我在聚合函数中执行相同的操作时 db.foo.aggregate( { $match: { $where: "this.conte
db.main.find( { $where: "this.content.indexOf('someString') != -1" } );
对于find函数来说,它工作得很好
但当我在聚合函数中执行相同的操作时
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/ } );
谢谢你,约翰尼,我想哪里效率更高。有什么比正则表达式更高效的吗?@Cherven
$where
显然效率更低;看。常规express是此用例最有效的解决方案。2016年更新:您现在应该创建一个文本索引,并使用$text
进行搜索。请参阅。@文本索引现在通常是更好的选择,但它不像正则表达式那样提供部分字符串匹配,所以这取决于。