Searching a value in a specific field in MongoDB F

2019-01-26 17:28发布

问题:

(MongoDB Full Text Search)

Hello, I have put some fields in index and this is how I could search for a search_keyword.

BasicDBObject search = new BasicDBObject("$search", "search_keyword"); 
BasicDBObject textSearch = new BasicDBObject("$text", search);

DBCursor cursor = users.find(textSearch);

I don't want search_keyword to be searched in all the fields specified in the index. *Is there any method to specify search_keyword to be searched in specific fields from the index??*

If so, please give me some idea how to do it in Java.

Thank you.

回答1:

If you want to index a single field and search for it then it is the way it works by default. Lets say you want to index the field companyName. When you perform $text search on this collection, only the data from the companyName field will be used because you only included that field in your index.

Now the second scenario, your $text index includes more than one field. In this case you cannot limit the search to only look for values indexed from a specific field. The $text index is constructed on the collection level and a collection can have at most one $text index. Your option to limit search on specific field in this case may be to use regex instead.

MongoDB has the flexibility to fulfil requirements of other scenarios, but you can also evaluate using other technologies if your application is heavily search-driven and you are primarily after a full-text search engine for locating documents by keyword with a rich query syntax. ElasticSearch might be an alternative here. It really depends on the type of the application and your needs.