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