I am currently studying Aggregation Pipeline by looking at MongoDB Documents.
While I was impressed by the capabilities of MongoDB Optimizer, I had one question. ????

https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization/#pipeline-sequence-optimization

It is said that the MongoDB Optimizer changes the example code as shown below.

from

{ $addFields: {
    maxTime: { $max: "$times" },
    minTime: { $min: "$times" }
} },
{ $project: {
    _id: 1, name: 1, times: 1, maxTime: 1, minTime: 1,
    avgTime: { $avg: ["$maxTime", "$minTime"] }
} },
{ $match: {
    name: "Joe Schmoe",
    maxTime: { $lt: 20 },
    minTime: { $gt: 5 },
    avgTime: { $gt: 7 }
} }

to

{ $match: { name: "Joe Schmoe" } }, // Change
{ $addFields: {
    maxTime: { $max: "$times" },
    minTime: { $min: "$times" }
} },
{ $match: { maxTime: { $lt: 20 }, minTime: { $gt: 5 } } },  // Change
{ $project: {
    _id: 1, name: 1, times: 1, maxTime: 1, minTime: 1,
    avgTime: { $avg: ["$maxTime", "$minTime"] }
} },
{ $match: { avgTime: { $gt: 7 } } }

The above code is readable, but requires optimization by the MongoDB optimizer.
The code below is less readable, but it doesn’t seem to need any optimization by optimzer.

If you are a developer who knows the optimization process, is it right to write the code above?

New contributor

홍찬희 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.