Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
    }
  ]
}
like image 613
aguwala Avatar asked Jan 27 '26 22:01

aguwala


1 Answers

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] }
like image 77
Xavier Guihot Avatar answered Jan 29 '26 13:01

Xavier Guihot