在我的当前项目中,我们使用Mongo来存储大量文档(约100亿个)。如何使用字段_id删除最旧的一半文档,因为如果我使用索引字段“时间戳”,在当前速度下该操作将需要约3年才能完成。
> now = new Date()
ISODate("2012-04-19T19:01:58.841Z")
> ms = now.getTime()
1334862118841
> sec = Math.floor(ms/1000)
1334862118
> hex = sec.toString(16)
4f906126
> id_string = hex + "0000000000000000"
4f9061260000000000000000
> my_id = ObjectId(id_string)
ObjectId("4f9061260000000000000000")
db.<collection>.remove({query})
将为返回的每个文档执行写操作,正如您所观察到的,对于大量文档来说可能速度过慢。只需找到中间的_id并删除所有旧条目:
Mongo shell:
// get total documents count / 2
var c = Math.floor( db.collection.stats()['count'] / 2 )
// find middle id
var mid_id = db.collection.find().skip(c).limit(1)[0]._id
// remove all ids older than the middle one
db.collection.remove({_id:{$lt:mid_id}})