title: MongoDB Java API: Full-text search
body: <p>I have a problem using Java API for MongoDB. I have created a query using Robomongo:</p>
  
  <pre><code>db.collection.find(
      {$text : {$search : "\"expression\" keyword"}},
      {score : {$meta : "textScore"}}
  ).sort({score : {$meta : "textScore"}})
  </code></pre>
  
  <p>Now I would like to create the same query using Java API:</p>
  
  <pre><code>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);
  </code></pre>
  
  <p>The problem is that this code does not work. The query:</p>
  
  <pre><code>DBObject searchCommand = new BasicDBObject(
      "$text", new BasicDBObject("$search", "\"expression\" keyword")
  );
  </code></pre>
  
  <p>works perfectly. After appending the second part all results become invisible. What's more, this line:</p>
  
  <pre><code>DBCursor result = collection.find(searchCommand).sort(sorting);
  </code></pre>
  
  <p>throws MongoException (BadValue bad sort specification). When I remove sort() method invocation the Exception is not present, but still I don't have any results (if I append "score").</p>
  
  <p>I have found a solution to this problem, but using Spring. I wouldn't like to use any other libraries. Also, I am a beginner in MongoDB. Thank you for your help and time, cheers.</p>
  
  <hr>
  
  <p>UPDATE. Problem solved. Appending "score" to query searchCommand passed as first parameter of find() is wrong. "Score" should be passed in separate DBObject as the second parameter of find() method as follows:</p>
  
  <pre><code>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);
  </code></pre>