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(); }); });
In MongoDB, projection means selecting only the necessary data rather than selecting whole of the data of a document. If a document has 5 fields and you need to show only 3, then select only 3 fields from them.
What are projection queries? In MongoDB, the default for queries is to return all fields in matching documents. A projection query is used to specify or restrict the data returned in query results. By specifying a projection query, you can specify the fields you want to return or exclude.
The _id field is included automatically unless specifically excluded.
One can use projection with db. collection. find() method. In this method, the second parameter is the projection parameter, which is used to specify which fields are returned in the matching documents.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With