projection not working with db.collection.find in mongo

snehal maheshwari picture snehal maheshwari · Jan 25, 2018 · Viewed 8.7k times · Source

I have started to use mongodb just a day back and have encountered an issue. I searched on net and stackoverflow for how to hide _id value in final answer and following the answers provided I tried to get my code run but still the _id part shows.

P.S.: I am using cloud9 as the ide.

var mongo = require('mongodb').MongoClient;
mongo.connect('mongodb://localhost:27017/learnyoumongo', function(err, database) {
        if(err) throw err;
        const db = database.db('learnyoumongo');
        var parrots = db.collection('parrots');
        parrots.find({
            age: { $gt: +process.argv[2] }
        },{
            name: 1,
            age: 1,
            _id: 0
        }).toArray(function(err, docs){
            if(err) throw err;
            console.log(docs);
            database.close();
        });
});

Answer

Jo Gro picture Jo Gro · Feb 4, 2018

you could separate projection like this:

    parrots.find({
        age: { $gt: +process.argv[2] }
    }).project({_id:0}).toArray(function(err, docs){
        if(err) throw err;
        console.log(docs);
        database.close();
    });

i had the same issue with being unable to get projection to work, and the above method worked for me