kalimba
kalimba

Reputation: 418

NodeJS mongo driver find statement with projection returning full document

I have below funtion to filter only order_id from info collection. Instead of getting _id and order_id callback is getting all key, values from database. Node version: 9.4 Mongo version: 3.4

var listCollections=function (columns,db,callback) {
    if (columns.length===0) {
        return callback('No columns specified')
    }
    columns.forEach(function (col) {
        query[col]=true;
    });
    db.collection('info').find({},{order_id:true}).toArray(function (mongoError,result) {
        console.log(result);
    });
};

Please correct me here, but as far as documentation of mongo driver goes, my syntax is correct. How do I get only specified columns from collection?

Upvotes: 0

Views: 1579

Answers (2)

Oleksandr Kyrpa
Oleksandr Kyrpa

Reputation: 678

Use "fields" option.

**db.collection('info').find({},{fields:{_id:0,name:1}}).toArray(function (mongoError,result) {
        console.log(result);
    })**

Upvotes: 1

Alex Blex
Alex Blex

Reputation: 37038

find method of the Collection accepts a single parameter in nodejs driver - the query itself.

projection is applied to the cursor:

db.collection('info')
  .find({})
  .project({order_id:1})
  .toArray(function (mongoError,result) {
    console.log(result);
  });

Upvotes: 2

Related Questions