---
title: "清理mongodb最老的数据"
author: "tanglei198577"
date: "2017-01-18T14:20:56Z"
tags: []
categories: ["数据库"]
slug: "mongodb"
draft: false
lastmod: "2017-01-18T14:20:56Z"
id: 2353743
url: "https://tanglei198577.iteye.com/blog/2353743"
---

```
public class MongoDBDataClean {

	public static void main(String[] args) throws Exception {
		
		TimerTask task = new TimerTask(){

			@Override
			public void run() {
               clearMongoData();
			}

			private void clearMongoData() {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				System.out.println("Start at : "+sdf.format(new Date()));
				
				MongoTemplate mongoTemplate = (MongoTemplate) SpringApplicationContextUtil.getInstance().getBean(
		                "mongoTemplate");
				Query query = new Query();
				query.sort().on("_id", Order.ASCENDING);
				List<HistoryEntry> list = mongoTemplate.find(query.limit(50000), HistoryEntry.class);
				
				System.out.println("Count end at :"+list.size()+"      "+sdf.format(new Date()));
				
				for(int i =0 ; i < list.size() ; i ++){
					mongoTemplate.remove(list.get(i));
				}
				System.out.println("Success end at :"+sdf.format(new Date()));
			}
		};
		
		Timer timer = new Timer();
		long delay = 0;
		long intevalPeriod = 60*1000;
		timer.scheduleAtFixedRate(task, delay, intevalPeriod);
	}
}
```