3
3
3042018-01-30 21:37:11
MongoDB
304, 2018-01-30 21:37:11

How to get only required fields?

I use mongo native driver for node.js
I need to get only 2 fields, now I implement it like this

return ( async() => {
    let res = await collection.findOne({username:userName});
    return {
      id : res.id,
      userName : res.username
    };
  })();

But so, I get the entire document, and then I filter it - it would be more productive to immediately get the required fields.
The docs say that you can pass the fields that you need to get into the argument (fields)
collection.findOne(query, [fields, [options]], callback);

I pass it like this
let res = await collection.findOne({username:userName},{id : true, username : true});

but the entire document is returned.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
RidgeA, 2018-01-30
@304

let res = await collection.findOne({username:userName},{projection:{id : 1, username : 1}});

fields - depricated
mongodb.github.io/node-mongodb-native/3.0/api/Coll...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question