I would like to have a fixed size array stored in one of my documents.
I.E. users collection has an array of reports. Each report has a timestamp. I want to sort the reports in the array such that the latest (newest) is at the beginning of the array.
I am trying to use the $slice method but I seem to be only able to keep the last N elements in the array. In my case I want to keep the first N elements in the array.
Is there any way that I can somehow keep the array ordered by newest time and only store N newest reports. That way when I query for the N latest reports I can just grab from the beginning of the array.
var newReport = ...;
db.users.update({{_id: id},$push: {reports: {$each: [newReport], $sort: {"updatedOn": -1}, $slice: -3}}})
That will sort newest to oldest but since the slice is negative the 3 oldest reports are kept in the array.
var newReport = ...;
db.users.update({{_id: id},$push: {reports: {$each: [newReport], $sort: {"updatedOn": 1}, $slice: -3}}})
That will sort oldest to newest, and the 3 newest reports will be kept by the list of reports is then order oldest to newest.
Am I doing this wrong?