简体   繁体   中英

MongoDB find field that is part of a longer string

I know how to search for a field that contains a part of my search in MongoDB & Node, or even if it is possible ie. Record:

{ name: "Hello my name is robinson" }

Query:

{ name: /robinson/i }

However I don't know how to do the reverse

ie: Query:

{ name: "Hello my name is robinson" }

Record:

{ name: "robinson" }

I am trying to make rules to categorise strings based on their content. Any help is much appreciated. Content may not always be broken down into words, otherwise I could have just done a split by space and searched for each one.

With a Text index you should be able to find documents from a phrase text search.

http://docs.mongodb.org/manual/reference/operator/query/text/#match-any-of-the-search-terms

If the search string is a space-delimited string, $text operator performs a logical OR search on each term and returns documents that contains any of the terms.

In your example, you create an index in the "name" field of your collection:

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

Then you can query with the $text operator:

db.collection.find({$text: { $search: "Hello my name is robinson"}})

As stated in the docs, the query returns documents that contains "Hello or my or name or is or robinson".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM