amit
amit

Reputation: 10261

MongoDB not limiting to queried fields

I have a mongodb query in which I am requesting for a limited number of fields. But it is still returning the entire row. Can someone help?

collection.find(
        { username: searchterm },
        { username: 1 }, 
        function(e, docs){
            console.log('---- DB RESULT');
            console.log(docs);
            res.writeHead(200, {'content-type': 'text/json' });
            res.write( JSON.stringify({ 'docs' : docs }) );
            res.end('\n');
        }
    );

Upvotes: 0

Views: 351

Answers (1)

robertklep
robertklep

Reputation: 203231

Since you're using the node-mongodb-native driver, this should work (provided that the number of results isn't too large, since toArray() reads all results into memory first before calling the callback):

collection.find(
  { username: searchterm },
  { username: 1 } // [ 'username' ] works too
).toArray(function(e, docs) {
  // TODO: handle error...
  console.log('---- DB RESULT');
  console.log(docs);
  res.writeHead(200, {'content-type': 'text/json' });
  res.write( JSON.stringify({ 'docs' : docs }) );
  res.end('\n');
});

If you expect a lot of results, you probably want to use streaming, perhaps using JSONStream:

// Create a cursor stream.
var stream = coll.find(...).stream();

// Set correct Content-Type.
res.setHeader('Content-Type', 'application/json');

// Pipe cursor stream, convert it to JSON, and write to the client.
stream.pipe(JSONStream.stringify()).pipe(res);

(I tested this with Express but I just noticed that you seem to be using plain http; I think it'll still work, though)

Upvotes: 3

Related Questions