Ming
Ming

Reputation: 740

How to return only selected fields from a text search using mongodb nodejs driver

I am using native mongodb nodejs driver to perform a text search against my mongodb database, I've written a simple code as following, which it works fine with no errors, but it returns all fields, and I tried to figure out how to return only fields that I am interested in, I have tried to find any document in wiki and manual , but no luck at all.

Can anyone please help?

Thanks

var dbclient = require('mongodb').MongoClient;
dbclient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
  var search;
  if (err) {
    callback(err, null);
    return;
  }
  search = {
    text: collection,
    search: "a test"
  };
  return db.command(search, function(err, o) {
    db.close();
    return callback(err, o);
  });
});

Upvotes: 1

Views: 1417

Answers (1)

Randall Hunt
Randall Hunt

Reputation: 12582

What you're looking for is the projection field.

It's documented here: http://docs.mongodb.org/manual/tutorial/search-for-text/#specify-which-fields-to-return-in-the-result-set

You could change your search variable to include the project field like this:

search = {
    text: collection,
    search: "a test",
    project: {"test": 1}
};

Upvotes: 1

Related Questions