Is it possible to limit the number of results coming in from a lookup stage?

Hi! I’m trying to perform a simple lookup stage, but the data in the “foreign” collection is quite big. Is there a way to limit that incoming data, so that I can get only one, or preferably, the latest record according to a field called timestamp specified in the incoming documents?

match_system = {
    '$match': {
        'name': 'LS-FB1-P-S'
    }
}


lookuptest = {
    '$lookup': {
        'from': 'log',
        'localField': 'name',
        'foreignField': 'server',
        'as': 'healthdocs'
    }
}

pipeline = [match_system, lookuptest]

result = hc.aggregate(pipeline)

Hi @mippzon
Welcome to the community forum!!

While using the aggregation pipeline, when you have result with the $lookup and $match, there can be two ways to display the most recent data or get only one data from all the documents of the resultant query.

  1. Using a $sort with $first to sort the data based on the ObjectId field.

P.S. The $first works is only meaningful when documents are in a defined order.

  1. $limit would also help in your case where you would want to display only the one response of the output documents.

Please let us know if you have further questions

Thanks
Aasawari

See MongoDB Aggregation - $nin match if value in array - #3 by steevej for an example of the concept mentioned by @Aasawari.