2

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

Community
  • 1
  • 1
Vignesh Subramanian
  • 7,161
  • 14
  • 87
  • 150

4 Answers4

4

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);
});
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
1

Have you tried:

db.<collection>.find({},{"Name": 1, "District": 1})
robjwilkins
  • 5,462
  • 5
  • 43
  • 59
1

While using monk, I prefer something like this

query={'userType':'crew'}; // condition to select users
query2=['_id' ,'firstname' , 'lastname'] ; //Array, Limit the fields to retrieve 
collection.find(query,query2, function(error,crew){
    if(error)
        response.send(error)
    else {
        response.send(crew);
    }
});

Please note that it is better to include "_id" otherwise ng-repeat will cause issues and you will have to iterate it using $index . Hope it helps

IrfanAnwar
  • 79
  • 1
  • 10
0
collection.find().select('field1,field2').then((data) =>{res.send(data)})
  • 1
    Welcome to Stack Overflow, and thank you for contributing an answer. Would you kindly edit your answer to to include an explanation of your code? That will help future readers better understand what is going on, and especially those members of the community who are new to the language and struggling to understand the concepts. That's especially important when there's already an accepted answer that's been validated by the community. Under what conditions might your approach be preferred? Are you taking advantage of new capabilities? – Jeremy Caney Aug 13 '21 at 20:02