Second parameter to limit fields in find() not wor

2019-01-29 01:49发布

问题:

Mongodb Database view

I want to omit the _id field in my result

MongoClient.connect("mongodb://localhost:27017/",function(err,client){
    var db = client.db("customerDetails");
    db.collection("customerName").find({},{ _id : 0}).toArray(function(error,result){
        console.log(result);
        client.close();
    });
});

Looked up from w3 schools

But somehow its not working. I still get the _id field in my result object. What am i missing ??

回答1:

In version 3.0 of the mongodb driver, the second parameter to find() is the options object, not the projection document. See the documentation here. To send a projection document, set the projection property of the options document. E.g.

db.collection("customerName").find({}, { projection: { _id: 0 } })

Alternatively, use the project method:

db.collection("customerName").find({}).project({ _id: 0 })

In version 2.2 of the mongodb driver, the second argument of find was indeed the projection document. This has changed in the latest version (3.0). So some blog posts might not be up to date. See the relevant section of the 3.0 changelog here.



回答2:

This should work. Using the boolean "false".

MongoClient.connect("mongodb://localhost:27017/",function(err,client){ var db = client.db("customerDetails"); db.collection("customerName").find({},{ _id : false}).toArray(function(error,result){ console.log(result); client.close(); }); });


回答3:

In version 3.4.9 of the mongodb you can simply achieve this by:

db.getCollection('data').find({}, { _id: 0 })


标签: mongodb