Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude fields from result in MongoDB monk

I want to exclude some fields from result. I have code:

users = db.select('users');

users.find( {}, { sort: { points:1 }, privateKey:0, publicKey:0}, function(err,data){      
  res.send(data);
});

I want to exclude private and public key from results. Can I do that using monk?

like image 859
Pikachu Avatar asked Mar 06 '14 16:03

Pikachu


3 Answers

For me, I need to use the .project() method:

const someFunction = async () => {

    const result = await users
        .find({}, { sort: { points: 1 })
        .project({ privateKey: 0, publicKey: 0});

};
like image 90
Alex Crist Avatar answered Oct 04 '22 21:10

Alex Crist


According to documentation first argument in find is filter and second is projection .But you have used sort . It will not able to interpret . You are trying to confuse projection with sort .Sorting should be after find and projection.

You can write projection like { field1: <boolean>, field2: <boolean> ... }

Note : The find() method always includes the _id field even if the field is not explicitly stated to return in the projection parameter.

 users.find({}, { privateKey: 0, publicKey: 0 }).sort({points: 1}).toArray(
           function (err, data) {
                      res.send(data);
             });
like image 41
Sumeet Kumar Yadav Avatar answered Oct 04 '22 19:10

Sumeet Kumar Yadav


You can also do it like this:

users.find( {}, { sort: { points:1 }, fields : { privateKey:0, publicKey:0} },
  function(err,data){      
    res.send(data);
  }
);
like image 36
Will Shaver Avatar answered Oct 04 '22 20:10

Will Shaver