Reputation: 3915
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.
Upvotes: 3
Views: 2068
Reputation: 42352
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.
Upvotes: 2
Reputation: 11737
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
Upvotes: 0
Reputation: 2375
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...?
Upvotes: 0
Reputation:
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.
Upvotes: 0