2
votes

Is it possible to create a capped sub-collection. I'm trying to do something like:

user = {
  name: String,
  latest_messages: [String]
}

Where the latest_messages are capped to 10.

If not, what do you suggest as an alternative?

Update 1:

It appears as though keeping the array capped manually is the only solution. Here's a way to do this:

joe = {name: 'Joe', latest_messages: ['', '', '', '', '', '', '', '', '', '']}
db.users.save(joe)

db.users.update({name: 'Joe'}, {$push: {'latest_messages': 'hello'}})
db.users.update({name: 'Joe'}, {$pop: {'latest_messages': -1}})

db.users.update({name: 'Joe'}, {$push: {'latest_messages': 'world'}})
db.users.update({name: 'Joe'}, {$pop: {'latest_messages': -1}})

Any suggestions on making this more efficient?

Update 2:

There's an open Jira ticket, "SERVER-1050" that requests to add the ability to do the two (push & pop) as one atomic operation.

4
see @asya-kamsky's answer - Artem Mezhenin

4 Answers

2
votes

As of version 2.4 there is a feature to allow doing this called "capped arrays". This allows you to $push documents to an array in conjunction with $each, $slice and $sort operators to add one or more documents to the array while maintaining given size, sorting by specified field of subdocuments.

See exact syntax and examples here.

0
votes

You can only specify the overall number of documents of a capped collection. There is no way limit the size of an array unless through some checks in your app.

0
votes

Maybe you can create a separate capped collection for each user? So the name of the collection is the name of each user. I don't know if MongoDB becomes slow if you have many collections? How many different users do you have? Something like 100, 1000, 10000...?

0
votes

There is a request on their JIRA board that is nearly 2 years old to do exactly this. It has been scheduled to be added to the next version of mongodb since 1.6 so I wouldn't hold your breath.

https://jira.mongodb.org/browse/SERVER-991