steevej
(Steeve Juneau)
August 18, 2022, 1:47pm
2
Very interesting topic.
See some of my previous posts that are related.
This is some kind of optimization that I came to appreciate. By doing it like this, duplicated values are $lookup-ed up only once save processing time on the server. It also preserve bandwith since duplicate resulting documents are not sent over the wire.
An alternative to the $unwind/$group would be $set stage where you use $map to complete the source array with the resulting array. That would negate the optimization supplied by default. But that’s fine because it would be your choice and …
Simply do exactly the same king of $project with $ifNull but for each value you want null.
It will get complex and ugly very fast as you will need to use $range to create you array indexes, $map to map each element to the existing element or to your default null using $ifNull.
But, my personal opinion, is that this king of null-ishing cosmetic manipulations are better done on the application data access layer rather than the data server. It is easier to scale the state-less data access layer …
The first thing is that you had foreignField:questionID rather than foreignField:questionId which was producing an empty usersAnswered.
The $lookup is smart enough to it over arrays so the next stage is simply
$lookup: {
from: "profiles",
localField: "usersAnswered.userID",
foreignField: "_id",
as: "profiles",
}
This will not be in the exact format you want as the profile data will not be inside the usersAnswered array but will be at t…
There are times where it is better to do things on the server. One such time is when it reduce the amount of data transferred. Using $map and $filter to only returned the subset of data of interest is definitively such a case.