Menu
CoddyTech

Choosing Returned Fields

Part of the Databases with MongoDB section of Coddy's Node.js journey. Lesson 10 of 29.

A list page may need titles without every other field. A projection chooses which fields the database returns. Put it in the second argument to find. A value of 1 includes a field.

await books.find({}, {projection: {title: 1, _id: 0}}).toArray();
// [{title:'Dune'}, {title:'Kindred'}, {title:'Emma'}]

The empty filter keeps every book. The projection changes each returned document, not which books match. MongoDB normally includes _id even when you select other fields; setting it to 0 omits it. The documents stored in the Data tab keep all their original fields.

challenge icon

Challenge

Easy

This is a small practice project. Its setup is provided; edit only exercise.js.

Return only title and year for every book. Omit _id and genre. Run and GET /result: the first result is {"title":"Dune","year":1965}. Check the Data tab: genre still exists in storage.

Try it yourself

export async function exercise(books) {
    return await books.find().toArray();
}

All lessons in Databases with MongoDB

Practice on your own: Express playground