MongoDB full text search using PHP

2019-03-05 22:36发布

问题:

It seems that my searching for how to do this brings back results that are a year old and apparently no longer work or I am not doing something correctly.

Through the MongoDB command line, I have run this for indexing:

db.collectiontest.ensureIndex( { "$**": "text" }, { name: "TextIndex" } )

Did this based on the example at

http://docs.mongodb.org/manual/tutorial/create-text-index-on-multiple-fields/

I do not receive an error when that is executed.

Here are 2 of the Stackoverflow postings I have tried:

How to search in fulltext index using php in mongodb

MongoDB Collection runCommand from PHP

The last post, I tried the accepted answer except the ensure index since I did that via command line and the poster's solution as well. Both methods returns a message showing "Array ( [errmsg] => no such cmd: text [bad cmd] =>" .

I'm running a vm of Ubuntu Server 12 with latest release versions of PHP and MongoDB.

Thanks,

James

回答1:

If you are using the latest version of mongodb, the correct syntax is

db.collection.ensureIndex(
                           {
                             subject: "text",
                             content: "text"
                           }
                         )

for indexing multiple text fields in a single collection, and

 db.collection.ensureIndex(
                               {
                                 content: "text"
                               }
                             )

for a single field. Try modifying your ensureIndex() call to match one of the above patterns and see if that works for you.

The correct query syntax can be found here: http://docs.mongodb.org/manual/reference/operator/query/text/

db.articles.find( { $text: { $search: "coffee" } } )