mongodb delete old chat
I want to delete old chat logs, meaning any records besides the 10 latest.
Here's how I'm getting the latest:
collection.find({"chatroom" : chatroom}).limit(10).sort({ time: -1 })
H开发者_高级运维ow do I delete everything else?
Thanks.
You can do a query to get the 10th oldest and then delete the ones older than that.
var oldest = find({"chatroom" : chatroom}).limit(1).skip(10).sort({ time: -1 }).next();
remove({"chatroom" : chatroom, time : {$lt : oldest.time }})
You have to iterate over each items of the result set and remove it individually if you get hold of the related documents through a proper filter.
How about using a capped collection?
Reserve enough space in size
argument and set max
to 10.
You might want to swtich sort({ time: -1 })
with sort({ $natural: -1 })
for better performance if you switch to a capped collection (where both orders would be the same I guess).
How frequently you need to do this? How many docs are we talking about?
One of the option: move the latest 10 to some temp collection empty the log collection reinsert from the temp collection
This might not be the optimal solution.
精彩评论