I have a problem using Java API for MongoDB. I created a query using Robomongo:
db.collection.find( {$text : {$search : "\"expression\" keyword"}}, {score : {$meta : "textScore"}} ).sort({score : {$meta : "textScore"}})
Now I would like to create the same query using the Java API:
DBObject searchCommand = new BasicDBObject( "$text", new BasicDBObject("$search", "\"expression\" keyword") ).append( "score", new BasicDBObject("'$meta'", "textScore") ); DBObject sorting = new BasicDBObject( "score", new BasicDBObject("'$meta'", "textScore") ); DBCursor result = collection.find(searchCommand).sort(sorting);
The problem is that this code does not work. Request:
DBObject searchCommand = new BasicDBObject( "$text", new BasicDBObject("$search", "\"expression\" keyword") );
works great. After adding the second part, all results become invisible. What else is this line:
DBCursor result = collection.find(searchCommand).sort(sorting);
throws a MongoException (BadValue bad sort specification). When I delete the call to the sort () method, there is no Exception, but still I have no results (if I add a "grade").
I found a solution to this problem, but using Spring. I would not want to use any other libraries. Also, I am new to MongoDB. Thanks for your help and time, greetings.
UPDATE The problem is solved. Adding a βscoreβ to a searchCommand query that passed as the first find () parameter is incorrect. The "score" must be passed in a separate DBObject as the second parameter to the find () method as follows:
DBObject search = new BasicDBObject( "$text", new BasicDBObject("$search", "\"expression\" keyword") ); DBObject project = new BasicDBObject( "score", new BasicDBObject("$meta", "textScore") ); DBObject sorting = new BasicDBObject( "score", new BasicDBObject("$meta", "textScore") ); DBCursor result = collection.find(search, project).sort(sorting);