Reputation: 7289
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
Upvotes: 2
Views: 4155
Reputation: 1
collection.find().select('field1,field2').then((data) =>{res.send(data)})
Upvotes: 0
Reputation: 79
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
Upvotes: 1
Reputation: 312045
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);
});
Upvotes: 4
Reputation: 5652
Have you tried:
db.<collection>.find({},{"Name": 1, "District": 1})
Upvotes: 1