...

/

Read Documents: Part 7

Read Documents: Part 7

Learn and practice projection while reading MongoDB documents.

Projection

The second argument to the find and findOne functions is a projection. It is a way to control what data the filter query returns.

Return specific fields

First, let’s insert some documents.

Press + to interact
db.tasks.insertMany([
{
name: 'Task 1',
priority: 1
},
{
name: 'Task 2',
priority: 2
}
]);

Next, we build a query to find documents and limit fields.

db.tasks.find({}, {name: 1});

This query returns the below output.

[
    { 
        _id: ObjectId("60fbf595b7b1ef7b709ecf28"), 
        name: 'Task 1' 
    },
    { 
        _id: ObjectId("60fbf595b7b1ef7b709ecf29"), 
        name: 'Task 2' 
    }
]

This returns only the name and ...