Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do field selection on find() in the mongodb native driver?

I am using the mongodb native driver for node.js and can't get to work the field selection. What I want to do is to limit fields to name. I do not want the 'last' in the output.

I am doing this:

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

But the log prints:

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

So there is no name in the output.


Update: I have tried an object instead of array -- did not work. The reason is really mixing inclusion and exclusion. You can't mix it. When I only had "name":true it worked.

like image 586
user3111525 Avatar asked Jan 08 '14 14:01

user3111525


People also ask

How do I select a specific field in MongoDB?

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

What is MongoDB native driver?

The native MongoDB driver for Node. JS is a dependency that allows our JavaScript application to interact with the NoSQL database, either locally or on the cloud through MongoDB Atlas.

How do I search for an object in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.


1 Answers

If you are using latest mongodb 3.0 nodejs driver, then try this code:

db.collection('test').find({}).project({name: 1, last: 1}).toArray();
like image 111
lee shin Avatar answered Sep 20 '22 13:09

lee shin