Filter $lookup results

佐手、 提交于 2019-12-06 09:18:24

You need to add another $project stage to your aggregation pipeline after the $lookup stage.

{ "$project": { 
    "id": "R1",
    "type": "xyz",
    "reportfile": {
        "$let": {
            "vars": { 
                "obj": {   
                    "$arrayElemAt": [
                        { "$filter": { 
                            "input": "$reportfile", 
                            "as": "report", 
                            "cond": { "$eq": [ "$$report.time", { "$max": "$reportfile.time" } ] }
                        }},
                        0
                    ]
                }
            },
            "in": { "id": "$$obj.id", "time": "$$obj.time" }
        }
    }
}}

The $filter operator "filter" the $lookup result and return an array with the document that satisfy your condition. The condition here is $eq which return true when the document has the $maximum value.

The $arrayElemAt operator slice the $filter's result and return the element from the array that you then assign to a variable using the $let operator. From there, you can easily access the field you want in your result with the dot notation.

What you would require is to run the aggregation operation on the reportfile collection, do the "join" on the reports collection, pipe a $group operation to ordered (with $sort) and flattened documents (with $unwind) from the $lookup pipeline. The preceding result can then be grouped by the reportid and output the desired result using the $first accumulator aoperators.


The following demonstrates this approach:

db.reportfiles.aggregate([
    { "$match": { "reportid": "R1" } },
    {
        "$lookup": {
            "from": 'reports',
            "localField" : 'reportid',
            "foreignField" : 'id',
            "as": 'report'
        }
    },
    { "$unwind": "$report" },
    { "$sort": { "time": -1 } },
    {
        "$group": {
            "_id": "$reportid",
            "type": { "$first": "$report.type" },
            "reportfile": {
                "$first": {
                    "id": "$id",
                    "reportid": "$reportid",
                    "time": "$time"
                }
            }
        }
    }
])

Sample Output:

{
    "_id" : "R1",
    "type" : "xyz",
    "reportfile" : {
        "id" : "F14",
        "reportid" : "R1",
        "time" : ISODate("2016-06-15T09:20:29.809Z")
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!