projection not working with db.collection.find in

2020-03-08 08:34发布

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();
        });
});

1条回答
Ridiculous、
2楼-- · 2020-03-08 08:58

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

查看更多
登录 后发表回答