Home > Back-end >  How to return a specific field in mongodb?
How to return a specific field in mongodb?

Time:11-28

Here is my code, it searches the word 'test' through all documents in 'subs' collection and return them. The thing is I just need two specific fields (id and name).

app.get('/', (req, res) => {
  db.collection('subs')

    .find({
      $text: { $search: 'test' },
    })
    .toArray((err, result) => {
      if (err) {
        throw new err();
      }
      res.json({
        length: result.length,
        body: { result },
      });
    });
});

CodePudding user response:

So you can use a projection: db.collection('subs').find({$text: { $search: 'test' }}, {name: 1 } ).

Read more about it here: https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/#return-the-specified-fields-and-the-_id-field-only

CodePudding user response:

you can set the fields you need in additional argument to the find method :

db.collection('subs').find({
  $text: { $search: 'test' }
}, 
{ 
  name: 1, 
  otherColumn: 1 
}); // select only the "name" & the "otherColumn" column

The _id column is always returned by default, but you could disable it by adding _id: 0.

Hope this solve your question.

CodePudding user response:

Finally I found the answer! :

.find(
      {
        name: { $in: ['Prison Break', 'Dexter'] },
        $text: { $search: 'kill' },
      },
      {
        projection: { name: 1 },
      }
    )
  • Related