0

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?

1
  • Is there any reason you can't store oldest-to-newest in the db and scan-from-end on the client side? That seems like a more natural solution. Commented Sep 19, 2013 at 19:44

1 Answer 1

1

Your second query should give you mostly what you're looking for. I agree with Amalia that it would be easier to get the correct order of the array in your application code.

However, there are some issues with the syntax of your second query. Update queries follow this pattern:

db.users.update({<query>}, {<update>})

Right now you're doing

db.users.update({<query, <update>})

If you change your query to

db.users.update({_id: id}, {$push: {reports: {$each: [newReport], $sort: {"updatedOn: 1}, $slice: -3}}})

It should work.

Sign up to request clarification or add additional context in comments.

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.