'How to get the last N elements of an array in mongoDB?

I have this collection example:

{
  "field1" : "A",
  "field2" : [
    {
      "val" : 1,
      "time" : ISODate("2010-07-13T00:18:35.178Z")
    },
    {
      "val" : 4,
      "time" : ISODate("2011-07-14T23:29:40.012Z")
    },
    {
      "val" : 8,
      "time" : ISODate("2012-07-14T23:29:45.012Z")
    },
    {
      "val" : 1,
      "time" : ISODate("2013-07-13T00:18:35.178Z")
    },
    {
      "val" : 2,
      "time" : ISODate("2014-07-14T23:29:40.012Z")
    },
    {
      "val" : 3,
      "time" : ISODate("2015-07-14T23:29:45.012Z")
    }
  ]
}

field2 is an array of documents and I can't get the last N documents.

For example, in this example I want to get the last 2 values:

{
  "field1" : "A",
  "field2" : [
    {
      "val" : 2,
      "time" : ISODate("2014-07-14T23:29:40.012Z")
    },
    {
      "val" : 3,
      "time" : ISODate("2015-07-14T23:29:45.012Z")
    }
  ]
}


Solution 1:[1]

Starting in Mongo 5.2, we can use the $lastN aggregation operator:

// { values: [1, 5, 4, 12, 3] }
// { values: [3] }
// { values: [7, 8, 2] }
db.collection.aggregate(
  { $set: { values: { $lastN: { n: 2, input: "$values" } } } }
)
// { values: [12, 3] }
// { values: [3] }
// { values: [8, 2] }

Solution 2:[2]

You can use the $slice projection operator with a negative value to get the last n elements of an array field:

db.collection.find({}, {field2: {$slice: -2}})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Xavier Guihot
Solution 2 JohnnyHK