Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js MongoDB Find with projection to exclude _id still returns it

Trying to follow the examples here to filter by using a projection to exclude _id. The _id still returns:

Code

var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/db1";  MongoClient.connect(url, function (err, db) {     if (err) throw err;     var dbase = db.db("db1"); //here          dbase.collection("customers").find(         {},         {             _id: 0          }         ).toArray(function(err, result) {         if (err) throw err;         console.log(result);         db.close();     });  }); 

Result still return as follows:

[ { _id: 5a2bb2d6ee48575cb54c4365, name: 'John', address: 'Highway 71' }, { _id: 5a2bb2d6ee48575cb54c436d, name: 'Susan', address: 'One way 98' }, .... { _id: 5a2bb2d6ee48575cb54c4371, name: 'Chuck', address: 'Main Road 989' }, { _id: 5a2bb2d6ee48575cb54c4372, name: 'Viola', address: 'Sideway 1633' } ]

Theoretically _id should not be part of what is returned. What is wrong here?

like image 681
ThrasosT Avatar asked Dec 09 '17 18:12

ThrasosT


People also ask

How do I exclude fields in MongoDB?

To exclude the _id field from the output documents of the $project stage, specify the exclusion of the _id field by setting it to 0 in the projection document.

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.

How do I get only certain fields in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});


1 Answers

To limit the fields you have to use fields option( dont know about new updates):

dbase.collection("customers").find({}, {     fields: { _id: 0 } }).toArray(function(err, result) {     if (err) throw err;     console.log(result);     db.close(); }); 

UPDATE:

For version > 3 you have to use projection option instead:

dbase.collection("customers").find({}, {     projection:{ _id: 0 } }).toArray(function(err, result) {     if (err) throw err;     console.log(result);     db.close(); }); 
like image 135
wrangler Avatar answered Sep 21 '22 16:09

wrangler