Here is the model 'Class' model for which I have created the "text" index for 'keywords','lifeArea',''type'.
Structure of the model:
{
"_id" : ObjectId("558cf6e3387419850d892712"),
"keywords" : "rama,seetha",
"lifeArea" : [
"Emotional Wellness"
],
"type" : "Pre Recorded Class",
"description" : "ram description",
"synopsis" : "ram syn",
"name" : "ram demo",
"__v" : 0
}
db.Class.getIndexes()
// displaying index
{
"v" : 1,
"key" : {
"_fts" : "text",
"_ftsx" : 1
},
"name" : "classIndex",
"ns" : "innrme.classes",
"weights" : {
"keywords" : 1,
"lifeArea" : 1,
"type" : 1
},
"default_language" : "english",
"language_override" : "language",
"textIndexVersion" : 2
}
I want to do a text search on the fields mentioned above. I tried the following query.
db.classes.find({$or:[{keywords: { $text: { $search: "rama abc" } } }, {type: {$text: { $search: "class" }}}],score: {$meta: 'textScore'}});
But it did not work and I got the follwing error
Error: error: {
"$err" : "Can't canonicalize query: BadValue unknown operator: $text",
"code" : 17287
}
Please help me to get the correct query. Please correct/educate me if I am wrong in asking the question or in explaining the problem
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.
An
$or
expression can only have one special index expression, being either "text" or "geospatial" in the arguments.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:
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:So to resolve this you need:
To have a MongoDB server version of 2.6 or greater that supports the
$text
syntax ( or live with command forms )To live with indexing over multiple fields and using a single index.
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.
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/