2012-10-12 13 views
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中用於查找和聚合功能。

回答

6

您可以使用一個regular expression

$match: { content: /someString/ } 

您應該使用正則表達式,而不是一個$wherefind情況下,也因爲它的效率更高。

db.main.find({ content: /someString/ }); 
+0

謝謝Johny,我認爲哪裏更有效率。比正則表達式更有效嗎? – Cherven

+2

@Cherven'$其中'肯定效率較低;請參閱[文檔中的大警告](http://docs.mongodb.org/manual/reference/operators/#_S_where)。正則表達式是這種用例的最有效的解決方案。 – JohnnyHK

+0

2016年更新:您現在應該創建一個文本索引,並使用'$ text'進行搜索。請參閱[聚合管道中的文本搜索](https://docs.mongodb.com/v3.2/tutorial/text-search-in-aggregation/)。 –