问题描述:

Is it possible to search a string if I have some data stored like

Names:

{

name: 'john'

},

{

name: 'pete'

},

{

name: 'jack smith'

}

Then I perform a query like

{ $stringContainsKeys: 'pete said hi to jack smith' }

and it would return

{

name: 'pete'

},

{

name: 'jack smith'

}

I'm not sure that this is even possible in mongoDB or if this kind of searching has a specific name.

网友答案:

Yes, quite possible indeed through the use of the $text operator which performs a text search on the content of the fields indexed with a text index.

Suppose you have the following test documents:

db.collection.insert([
    {
        _id: 1, name: 'john'
    },
    {
        _id: 2, name: 'pete'
    },
    {
        _id: 3, name: 'jack smith'
    }
])

First you need to create a text index on the name field of your document:

db.collection.createIndex( { "name": "text" } )

And then perform a logical OR search on each term of a search string which is space-delimited and returns documents that contains any of the terms

The following query searches specifies a $search string of six terms delimited by space, "pete said hi to jack smith":

db.collection.find( { "$text": { "$search": "pete said hi to jack smith" } } )

This query returns documents that contain either pete or said or hi or to or jack or smith in the indexed name field:

/* 0 */
{
    "_id" : 3,
    "name" : "jack smith"
}

/* 1 */
{
    "_id" : 2,
    "name" : "pete"
}
网友答案:

Starting from Mongodb 2.6 you can search mongodb collection to match any of the search terms.

 db.names.find( { $text: { $search: "pete said hi to jack smith" } } )

This will search for each of the terms separated by space. You can find more information about this at http://docs.mongodb.org/manual/reference/operator/query/text/#match-any-of-the-search-terms

However, it will work only with individual terms. If you have to search for exact phrase which is not a single term, e.g. you want to find "jack smith', but not "smith jack", it will not work, so you will have to use search for a phrase. http://docs.mongodb.org/manual/reference/operator/query/text/#search-for-a-phrase which searches for exact phrases in the text.

If you need more advanced text-based search features in your application, you might consider using something like Elasticsearch https://www.elastic.co/guide/en/elasticsearch/reference/1.3/query-dsl-mlt-field-query.html.

Zoran

相关阅读:
Top