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")
}
]
}
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] }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With