Searching in MongoDB

前端 未结 2 1712
渐次进展
渐次进展 2021-01-22 02:38

Imagine you need to implement a search in MongoDB. You have collection of documents that look like this:

{text: \"This is some Text }
{text: \"this is another te         


        
相关标签:
2条回答
  • 2021-01-22 03:29

    Might be fun to do a Map Reduce:

    mapper=function(){
        var words=this.text.match(/\S+\s*/g);
        for (w in words){
            emit(this._id, {'words':words})
        }
    }
    
    reducer=function(k,v){return {'words':this[0].words}}
    

    This should get you a collection with the words separated out. There's probably a way of doing this with aggregations.

    0 讨论(0)
  • 2021-01-22 03:32

    Maybe the full-text-search is your answer http://docs.mongodb.org/manual/core/index-text/ http://docs.mongodb.org/manual/reference/operator/query/text/

    Code snippets from these references:

    1 - db.comments.ensureIndex( { comments: "text" } )
    

    The following code searches for comments that contain the words This or another but do not contain the term hehe:

    2- db.comments.find( { $text: { $search: "This another -hehe" } } )
    
    0 讨论(0)
提交回复
热议问题