How to make field selection in find () in mongodb native driver?

I am using my own mongodb driver for node.js and cannot work with field selection. What I want to do is restrict the fields for the name. I do not want the "last" in the output.

I'm doing it:

db.collection("test").find({},[{'name':true,'last':false}]).toArray(function(err, results) { console.dir(results); }); 

But the magazine prints:

 [ { _id: 524b53588aa4f388de1c2ddb }, { _id: 524b53548aa4f388de1c2dda } ] 

So there is no name on the output.


Update : I tried an object instead of an array - it did not work. The reason is that they really mix inclusion and exclusion. You cannot mix it. When I only had "name":true , it worked.

+7
mongodb
source share
4 answers

The field selection argument for find is an object, not an array. And you cannot mix the inclusion and exclusion of a field (except _id ), so it should be:

 db.collection("test").find({}, {'name': true}).toArray(function(err, results) { console.dir(results); }); 
+15
source share

If you are using the latest muzodb 3.0 nodejs driver, try this code:

 db.collection('test').find({}).project({name: 1, last: 1}).toArray(); 
+4
source share

Omit array:

 db.collection("test").find({},{'name':true,'last':false}).toArray(function(err, results) { console.dir(results); }); 
0
source share

The recommended way to do this in v3.0 is with the projection field in the options object:

 db.collection('test').find({}, {projection: {name: 1}}).toArray() 

As mentioned in the accepted answer, you still can't mix inclusion and exclusion.

See: http://mongodb.imtqy.com/node-mongodb-native/3.0/api/Collection.html#find

0
source share

All Articles