Fabdol
Fabdol

Reputation: 129

How to return a specific field in mongodb?

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 },
      });
    });
});

Upvotes: 0

Views: 2679

Answers (3)

Fabdol
Fabdol

Reputation: 129

Finally I found the answer! :

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

Upvotes: 1

Tisamu
Tisamu

Reputation: 154

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.

Upvotes: 2

Stoobish
Stoobish

Reputation: 1382

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

Upvotes: 1

Related Questions