Need help with specific aggregation

I cannot figure out how to do the aggregation in compass on the following data for which I want:
I want only these documents where the last element of the ‘versions’ array has ‘version_status’ = ‘MERGED’ and return the entire document.

{
    "_id": {
        "$oid": "6407581b1f37c526aa6e0af3"
    },
    "field1": "12211",
    "field2": "ABC",
    "field3": "ABC",
    "field4": "ABC",
    "versions": [{
        "version": "1",
        "version_create_datetime": "202303071028",
        "version_created_by": "ENTITY",
        "version_source_file": "123.txt",
        "version_status": "MERGED",
        "my_data": {
            "field4": "01",
            "field4": "04",
            "field4": "03",
        }
    }]
}

Thanks!

Sometimes, things are simpler than what we think.

c.find( { "$expr" : { "$eq" : [ { "$last" : "$versions.version_status" } , "MERGED" ] } } )

From the $last documentation:

New in version 4.4.

and

The $last operator is an alias for the following $arrayElemAt expression:

{ $arrayElemAt: [ <array expression>, -1 ] }

Thanks Steeve…I was trying similar with find yesterday before posting this, and cannot get it to work. However this aggregation pipeline does work…I’ll try your find approach again soon to see if I can get it to function.

– my pipeline

[{$project: {
 field1: 1,
 last: {
  $arrayElemAt: [
   '$versions',
   -1
  ]
 }
}}, {$match: {
 'last.version_status': 'MERGED',
 last.version_create_datetime: {
  $gt: '2023-03-07',
  $lt: '2023-03-08'
 }
}}, {$out: 'output_log_collection'}]
1 Like