5

I am looking to implement a time based queue with a fixed length where the old items pop off the back.

For instance I have a list of comments constrained to 10 items, the 11th item comes in and the oldest on falls off the back.

If not supported in Mongoose, can someone tell me some trickery I can use? (pre / etc)

Many Thanks

3 Answers 3

3

MongoDB has introduced capped arrays (from v2.4) which could be used to limit the number of elements in an array.

You can see some examples at limit number of elements

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

2 Comments

Any specific examples around mongoose?
i haven't got much experience on the mongoose, sorry.
1
db.myCollection.update({"arrayField.10": {$exists: true}}, {$pop: {"arrayField": 1}})

The "a.10" key checks if element 10 exists in "arrayField", which would mean the array size is equal to or greater than 10. If it does, pop 1 element off the back of the array atomically.

May not be the best solution for your case, but hopefully this may set you off in the right direction.

1 Comment

Correct, this query is native mongo.
1

According to Mongoose Wiki - it now supports MongoDB's capped arrays:

Mongoose 3.6 supports these new MongoDB 2.4 array operators.

Model.update(matcher, { $push: { docs: { $each: [{ x: 1 }, { x: 23 }, { x: 5 }], $slice: -2, $sort: { x: 1 }}}})

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.