I have a document that lists post item ids for an author separated out by topic. This results in a document such as the following:
{
_id: "sdkafjsadkfjads3023",
Author: "SomeGuy"
RecentPosts: {
"topic-1": {
Count: 4,
Posts: ["postitemid1","postitemid2","postitemid2","postitemid3"]
}
"topic-2": {
Count: 3
Posts: ["postitem5","postitem6","postitem8"]
}
}
}
Most of the time I am doing atomic pushes to each of these post arrays in the same update. What I want to do is limit the arrays above to 10 items at all times. This way, anytime I do a pushall to the same topic/posts. Is what I'm asking even possible, or should I do this a different way?
Thanks in advance
As it turns out, this was a longstanding issue in MongoDB that was since added in MongoDB 2.4 release using the $slice operator.
db.students.update(
{ _id: 1 },
{ $push: { scores: { $each : [
{ attempt: 3, score: 7 },
{ attempt: 4, score: 4 }
],
$sort: { score: 1 },
$slice: -3
}
}
}
)
http://docs.mongodb.org/manual/tutorial/limit-number-of-elements-in-updated-array/