删除mongodb中的旧记录 [英] Remove old records in mongodb
问题描述
我在Mongo DB中具有以下类型的记录.
I have records of the following type in Mongo DB.
{
"_id" : ObjectId("50217d8874ebb0e4e52cc07d"),
"timestamp" : "8/7/12 1:41:36 PM Pacific Daylight Time",
"_ts" : ISODate("2012-08-07T20:41:44.119Z")
}
如何删除旧记录?我已经尝试过类似db.offlineLogs.remove({timestamp: {$lt:new Date("2012, 8, 3")}});
的方法,但是它不起作用.
How do I remove old records? I have tried something like db.offlineLogs.remove({timestamp: {$lt:new Date("2012, 8, 3")}});
, but it doesn't work.
推荐答案
在您的原始查询中,timestamp
只是一个字符串字段,而Date()
在Mongo shell中将被视为字符串.比较这些操作数将像其他任何字符串比较一样工作:
In your original query, timestamp
is simply a string field and Date()
will be treated as a string in the Mongo shell. Comparing those operands will work like any other string comparison:
$ mongo
MongoDB shell version: 2.2.0-rc1-pre-
connecting to: test
> db.foo.drop()
true
> db.foo.insert({ x: Date() });
> db.foo.find()
{ "_id" : ObjectId("50218e808930273947a21cf3"), "x" : "Tue Aug 07 2012 17:54:09 GMT-0400 (EDT)" }
> sleep(1000)
null
> db.foo.find({ x: { $lt: Date() }});
{ "_id" : ObjectId("50218e808930273947a21cf3"), "x" : "Tue Aug 07 2012 17:54:09 GMT-0400 (EDT)" }
> db.foo.find({ x: { $gt: Date() }});
>
ISODate()
是 Mongo日期字段的JS等效项,而不是 Mongo日期字段与使用$gt
或$lt
运算符时的字符串值可比:
ISODate()
is the JS equivalent for Mongo date fields, and it is not comparable with string values when using the $gt
or $lt
operators:
> db.foo.find({ x: { $gt: ISODate() }});
> db.foo.find({ x: { $lt: ISODate() }});
> db.foo.find({ x: { $ne: ISODate() }});
{ "_id" : ObjectId("50218e808930273947a21cf3"), "x" : "Tue Aug 07 2012 17:54:09 GMT-0400 (EDT)" }
> db.foo.insert({x: ISODate() });
> db.foo.find({ x: {$gt: Date() }});
> db.foo.find({ x: {$lt: Date() }});
{ "_id" : ObjectId("50218e808930273947a21cf3"), "x" : "Tue Aug 07 2012 17:54:09 GMT-0400 (EDT)" }
> db.foo.find({ x: {$ne: Date() }});
{ "_id" : ObjectId("50218e808930273947a21cf3"), "x" : "Tue Aug 07 2012 17:54:09 GMT-0400 (EDT)" }
{ "_id" : ObjectId("50218fa18930273947a21cf4"), "x" : ISODate("2012-08-07T21:58:57.350Z") }
>
Mongo确实定义了比较之间的订单类型,其中字符串位于日期之前,但是与排序顺序有关,当同一字段在整个集合中可能具有不同的类型时.
Mongo does define compare orders between types, in which strings come before dates, but that relates to sort order when the same field may have different types across the collection.
请注意,如果您想自己做一些事情(例如在批处理过程中),如果要删除旧记录,您可能会对中对该主题进行了有趣的介绍.此博客条目.
Note that if removal of old records if something you envision yourself doing often (e.g. in a batch process), you may be interested in TTL collections, which are a new feature in the upcoming 2.2 release. Kristina Chodorow also wrote an amusing introduction on the topic in this blog entry.
这篇关于删除mongodb中的旧记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!