How to do multiple text search using “$text query and $or” in mongodb / mongoose?

前端 未结 2 1307
清酒与你
清酒与你 2021-01-15 21:21

Here is the model \'Class\' model for which I have created the \"text\" index for \'keywords\',\'lifeArea\',\'\'type\'.

Structure of the model:

{
            


        
相关标签:
2条回答
  • 2021-01-15 21:43

    First of all I don't think you can use $text in that manner, you need first to create a text index on the collection then you can use it but without specifying any field because it works on indexes not fields.

    Please check here: http://docs.mongodb.org/manual/administration/indexes-text/

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

    That actual error suggests your mongodb is a version less than 2.6 ( so no text search in that way ). But you cannot do that anyway for two reasons.

    1. An $or expression can only have one special index expression, being either "text" or "geospatial" in the arguments.

    2. You are expecting text searches on "two" different fields and you can only have one text index per collection. However that single index can be spread over several fields in the document. But you cannot ask different search terms for different fields.

    Documentation quote:

    You cannot combine the $text expression, which requires a special text index, with a query operator that requires a different type of special index. For example you cannot combine $text expression with the $near operator.

    And it should also say "You cannot use $or with a $text expression or the $near operator where either are used in more than one condition." But that little piece of information is missing, but you still cannot do it.

    Your syntax is generally not correct, but even with the correct syntax in a supported version of MongoDB you would get an error trying to use $or like this:

    Error: error: {
        "$err" : "Can't canonicalize query: BadValue Too many text expressions",
        "code" : 17287
    }
    

    So to resolve this you need:

    1. To have a MongoDB server version of 2.6 or greater that supports the $text syntax ( or live with command forms )

    2. To live with indexing over multiple fields and using a single index.

    3. To execute "separate queries" in place of your "or" conditions and "combine" the results in your client API interface.

    That is the only way you get "or" conditions like this with MongoDB text search.

    0 讨论(0)
提交回复
热议问题