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.
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
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.
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.
If you are using latest mongodb 3.0 nodejs driver, then try this code:
db.collection('test').find({}).project({name: 1, last: 1}).toArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With