Mongo DB使用remove命令删除旧数据 [英] Mongo DB remove old data using remove command

查看:385
本文介绍了Mongo DB使用remove命令删除旧数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的mongo数据库包含

My mongo db contains

> db.collection.find();
{ "_id" : ObjectId("55f8e493d97731874b1235bd"), "Date" : "14-12-2014", "Value" : 25.36 }
{ "_id" : ObjectId("55f8e497d97731874b1235be"), "Date" : "14-11-2014", "Value" : 25.36 }
{ "_id" : ObjectId("55f917f748f91b35cf1ddaac"), "Date" : "14-01-2015", "Value" : 25.36 }
{ "_id" : ObjectId("55f917fc48f91b35cf1ddaad"), "Date" : "14-02-2015", "Value" : 25.36 }
{ "_id" : ObjectId("55f9180148f91b35cf1ddaae"), "Date" : "14-03-2015", "Value" : 25.36 }
{ "_id" : ObjectId("55f9180848f91b35cf1ddaaf"), "Date" : "14-04-2015", "Value" : 25.36 }
{ "_id" : ObjectId("55f9180f48f91b35cf1ddab0"), "Date" : "14-05-2015", "Value" : 25.36 }
{ "_id" : ObjectId("55f9181448f91b35cf1ddab1"), "Date" : "14-06-2015", "Value" : 25.36 }
{ "_id" : ObjectId("55f9181948f91b35cf1ddab2"), "Date" : "14-07-2015", "Value" : 25.36 }
{ "_id" : ObjectId("55f9181d48f91b35cf1ddab3"), "Date" : "14-08-2015", "Value" : 25.36 }

我想删除三个月旧数据。为此

I want to delete three months old data. For that

> db.collection.remove( { "Date": {$lt:"14-10-2014"} } );

我尝试过这样,但无法正常工作。它只是根据月份删除它从今天删除到2014年的第2105年和第9个月到an 2104但不是12月和11月2104.我如何解决这个问题?

I tried like this but it's not working properly. It's deleting depending only on month e.g. it's deleting from today to jan 2105 and ninth month of 2014 to jan 2104 but not December & November of 2104. How do I solve this?

推荐答案

我想你可以尝试下面的代码。您可以删除文档,而不更新日期字段以 ISODate 。作为一个很好的做法,您应该始终将日期存储为 ISODate 。它使查询变得简单。

I think you can try the below code. You can remove the docs without updating the Date field to ISODate. As a good practice, you should always store date as an ISODate. It makes querying easy.

var cursor = db.collection.find()
while (cursor.hasNext()) {
 var doc = cursor.next();
 var docDate = doc.Date;
 var queryDate = "14-10-2014";
 var docDateMillis = new Date(docDate.substring(6,10), docDate.substring(3,5)-1, docDate.substring(0,2)).getTime();
 var queryDateMillis = new Date(queryDate.substring(6,10), queryDate.substring(3,5)-1, queryDate.substring(0,2)).getTime()
 if(docDateMillis < queryDateMillis) {
   db.collection.remove({_id : doc._id})
 }     
}

这篇关于Mongo DB使用remove命令删除旧数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆