1
我需要在MongoDB查詢中實現fieldValue.contains(「someString」)搜索嗎?如何在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
}
的問題是:如何寫一個fieldValue.contains( 「someString」)查詢在MongoDB中用於查找和聚合功能。
謝謝Johny,我認爲哪裏更有效率。比正則表達式更有效嗎? – Cherven
@Cherven'$其中'肯定效率較低;請參閱[文檔中的大警告](http://docs.mongodb.org/manual/reference/operators/#_S_where)。正則表達式是這種用例的最有效的解決方案。 – JohnnyHK
2016年更新:您現在應該創建一個文本索引,並使用'$ text'進行搜索。請參閱[聚合管道中的文本搜索](https://docs.mongodb.com/v3.2/tutorial/text-search-in-aggregation/)。 –