MongoDB query projections explained

Photo by Rubaitul Azad on Unsplash

Retrieving only what you need from a database is crucial for performance. MongoDB query projections help us achieve that by specifying which fields to include or exclude in the result set. In this article, we’ll explore how to use query projections in MongoDB with Node.js. We’ll cover basic and advanced projections, and dive into different ways of defining projections, including the string-based approach.

What Are Query Projections?

Query projections in MongoDB allow you to control which fields are returned in the query results. This is particularly helpful for optimizing bandwidth and improving query performance.

Basic Projections

Let’s consider a students collection with the following document structure:

{
"_id": "someId",
"name": "John",
"age": 21,
"email": "john@example.com"
}

Include Specific Fields

Using the native MongoDB driver in Node.js, you can define a projection like this:

const { MongoClient } = require('mongodb');

const client = new MongoClient("mongodb://localhost:27017");
await client.connect();
const db = client.db("testDB");
const cursor = db.collection("students").find({}, { projection: { name: 1, age: 1 } });

Exclude Specific Fields

To exclude specific fields:

const cursor = db.collection("students").find({}, { projection: { email: 0 } });

Note: Excluding and including fields in the same projection is not allowed, except for the _id field.

Advanced Projections

Using $slice for Arrays

If you have an array in your document and want to limit the elements returned:

const cursor = db.collection("students").find({}, { projection: { scores: { $slice: 5 } } });

Using $elemMatch

To return specific elements from an array based on a condition:

const cursor = db.collection("students").find({}, { projection: { scores: { $elemMatch: { $gt: 80 } } } });

String-based Projections

You can also use a string to define the projection. The syntax is simpler but less flexible:

const { MongoClient } = require('mongodb');

const client = new MongoClient("mongodb://localhost:27017");
await client.connect();
const db = client.db("testDB");

// Using Mongoose
const students = await Student.find({}, 'name age -_id');
// Using native MongoDB driver
const cursor = db.collection("students").find({}, { projection: 'name age -_id' });

In the string-based approach, a space-separated list of field names defines the fields to include. To exclude a field, prefix it with a -.

Summary

MongoDB query projections are an essential tool for optimizing your queries. Whether you are using basic or advanced projections, or different ways of defining them like string-based projections, understanding this feature can substantially improve the performance and efficiency of your Node.js applications.

,