Select only two fields in the mongodb using the monk

advertisements

My document has around 20 fields in it

I want to select only 2 fields and ignore other fields

I tried the below code as suggested here

collection. find({}, {  Name: 1, District: 1,_id:0},{limit:5}, function (e, docs) {
        res.json(docs);
    });

But its returning all fields. I want to get only name and district.

i.e I have Name,District,Country,Pincode,PhoneNumber, emailId,photo and many other fields. I want to select only Name and District.

P.S I am looking for ways other than giving all other field names as 0

I am using Monk


When using Monk, pass the fields to select as a string containing space-delimited field names, using a - prefix to exclude a field.

collection.find({}, 'Name District -_id', function (e, docs) {
    res.json(docs);
});

You can also pass the field selections as an array of strings:

collection.find({}, ['Name', 'District', '-_id'], function (e, docs) {
    res.json(docs);
});