Ayush
Ayush

Reputation: 57

how to find a single field in mongoDB instead of entire document

I want to achieve the result as obtained by

SELECT AGE FROM COLL WHERE NAME="AYUSH";

I took the following approach

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("new");
  //var query = { name:'ayush' };
  //var age = {age : 1, _id:0};
  dbo.collection("coll").find( 
       { name:'ayush' },
       { age : 1, _id:0}).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
  });
});

the result that i am getting is

[ { _id: 5a818b71d2029813505d736a,
name: 'ayush',
age: '22',
sex: 'm' } ]

Upvotes: 1

Views: 9519

Answers (2)

Ayush
Ayush

Reputation: 57

The easiest way to do this would be to convert the result in to an array and then send that array as the response.

The code would look like:

dbo.collection("coll").find( 
       { name:'ayush' },
       { age : 1, _id:0}).toArray(function(err, result) {
    if (err) throw err;
    var array = [];
    array.push(result[0].age);
    res.send(array);});

Moreover don't use mongoClient,use mongoose instead.its easier and better

Upvotes: 0

Mickael
Mickael

Reputation: 4558

From MongoDB documentation : Project Fields to Return from Query

Return the Specified Fields and the _id Field Only

A projection can explicitly include several fields by setting the <field> to 1 in the projection document. The following operation returns all documents that match the query. In the result set, only the item, status and, by default, the _id fields return in the matching documents.

db.inventory.find( { status: "A" }, { item: 1, status: 1 } )

The operation corresponds to the following SQL statement:

SELECT _id, item, status from inventory WHERE status = "A"

In your case, if you only want the field age, you have to suppress the other fields _id, name and sex as following :

dbo.collection("coll").find({ name:'ayush' },{age:1, _id:0, name:0, sex:0})...

Upvotes: 3

Related Questions