3

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")
    }
  ]
}

2 Answers 2

2

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] }
Sign up to request clarification or add additional context in comments.

Comments

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}})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.