Add field on document, compared to the rest of documents

I think its better to do in your client side language, or You can use the $function operator to define custom functions to implement behavior not supported by the MongoDB Query Language. See also $accumulator Start from MongoDB v4.4.

You can change JS code inside $function as per your understanding,

Stage 1: Group all in a array
Stage 2:

{
    $project: {
        allDocs: {
            $function: {
                body: function(allDocs) {
                    var length, score, time;
                    for (var i=0; i<allDocs.length; i++) {
                        if (!length || allDocs[i].length > length.length) length = allDocs[i];
                        if (!score || allDocs[i].score > score.score) score = allDocs[i];
                        if (!time || allDocs[i].time > time.time) time = allDocs[i];
                    }
                    for (var i=0; i<allDocs.length; i++) {
                        if (allDocs[i]._id == length._id) allDocs[i].lengthProp = "maxValue";
                        if (allDocs[i]._id == score._id) allDocs[i].scoreProp = "maxValue";
                        if (allDocs[i]._id == time._id) allDocs[i].timeProp = "maxValue";
                    }
                    return allDocs;
                },
                args: ["$allDocs"],
                lang: "js"
            }
        }
    }
},

Stage 3: unwind array
Stage 4: replace object to root

You can skip 3rd and 4th stages, query will return only single document and we know the field name is allDocs, can directly access like queryResult[0]['allDocs'].

1 Like