Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

projection not working with db.collection.find in mongo [duplicate]

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();         }); }); 
like image 621
snehal maheshwari Avatar asked Jan 25 '18 20:01

snehal maheshwari


People also ask

How do I write a projection query in MongoDB?

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 is the purpose of a projection in a find query for MongoDB?

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.

Which field is always included in a projection unless specifically excluded?

The _id field is included automatically unless specifically excluded.

Which of the following command is used for projection in MongoDB?

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.


1 Answers

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

like image 63
Jo Gro Avatar answered Sep 29 '22 11:09

Jo Gro