29

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?

ThrasosT
  • 307
  • 1
  • 3
  • 5

3 Answers3

56

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();
});
Kaspar Lee
  • 5,446
  • 4
  • 31
  • 54
wrangler
  • 3,454
  • 1
  • 19
  • 28
  • Finally I find the answer I was looking for ! Any idea why I didn't find anything about this 'fields' key in the documentation ? – Caillou Feb 22 '18 at 14:37
  • Finally find the answer as well. The official documentation does not state anything about the 'fields' – vilelam Mar 01 '18 at 19:09
19

In version 3 of the MongoDB API, the fields option has been deprecated. You should now use the projection option instead.

For example:

dbase.collection('customers').find({}, {
    projection: {
        _id: 0
    }
}).toArray(function (err, result) {
    if (err) {
        throw err
    }

    console.log(result)
    db.close()
})

The full list of supported options can be found here: http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#find

5

Starting in version 3.4, there is now an option for adding .project() outside of find().

Using ES8 async,await.

Ex:

async function connectDB(url) {

  try {
    const db = await MongoClient.connect(url);     
    const dbase = db.db("db1"); //here  
    
    const results = await dbase.collection("customers").find().project({_id:0}).toArray();

       console.log(result);
       db.close();
  }
  catch(err) {
    throw err;
  }
 }

Docs here and another example here.

Steven Spungin
  • 27,002
  • 5
  • 88
  • 78
Stephen Romero
  • 2,812
  • 4
  • 25
  • 48