Manoj bhat Manoj bhat - 4 months ago 11
Node.js Question

Query individual field using mongodb

Here in below code i am trying to log a single fetched document but entire document content is logged..what could be the possible solution..

var findDocuments = function(db, callback) {
var collection = db.collection('DATA');
collection.find({'borough':'Bronx'}).toArray(function(err, docs) {
assert.equal(err, null);
console.log("Found the following records");
console.log(docs);
callback(docs);
});
}

output :
[ { _id: 57a47c4a0d0c207a3e0efcc9,
address:
{ building: '1007',
coord: [Object],
street: 'Morris Park Ave',
zipcode: '10462' },
borough: 'Bronx',
cuisine: 'Bakery',
grades: [ [Object], [Object], [Object], [Object], [Object] ],
name: 'Morris Park Bake Shop',
restaurant_id: '30075445' }
]

Answer

To project specific field while using find query use the following syntax

collection.find({'borough':'Bronx'}, {borough:1}).toArray(function(err, docs) {
  assert.equal(err, null);
  console.log("Found the following records");
  console.log(docs); // will be array with only borough field and _id
  callback(docs);
 });