documents怎么可能是MongoDB中的moved from one collection to another collection??例如:我在集合A中有很多文档,我想将所有1个月前的文档移动到集合B(这些1个月前的文档不应该在集合A中).
用aggregation我们可以做copy.但我要做的是moving份文件.
documents怎么可能是MongoDB中的moved from one collection to another collection??例如:我在集合A中有很多文档,我想将所有1个月前的文档移动到集合B(这些1个月前的文档不应该在集合A中).
用aggregation我们可以做copy.但我要做的是moving份文件.
Update 2
请不要再对这个答案投赞成票了.正如书面所写,@jasongarber's answer在任何方面都更好.
Update
This answer by @jasongarber是一种更安全的方法,应该用它来代替我的.
如果我答对了,您希望移动所有超过1个月的文档,并且您使用mongoDB 2.6,那么没有理由不使用批量操作,这是我所知道的执行多个操作的最有效方式:
> var bulkInsert = db.target.initializeUnorderedBulkOp()
> var bulkRemove = db.source.initializeUnorderedBulkOp()
> var date = new Date()
> date.setMonth(date.getMonth() -1)
> db.source.find({"yourDateField":{$lt: date}}).forEach(
function(doc){
bulkInsert.insert(doc);
bulkRemove.find({_id:doc._id}).removeOne();
}
)
> bulkInsert.execute()
> bulkRemove.execute()
这应该非常快,而且它的优点是,如果在批量插入过程中出现问题,原始数据仍然存在.
Edit
为了防止占用过多内存,您可以对每处理x
个文档执行批量操作:
> var bulkInsert = db.target.initializeUnorderedBulkOp()
> var bulkRemove = db.source.initializeUnorderedBulkOp()
> var x = 10000
> var counter = 0
> var date = new Date()
> date.setMonth(date.getMonth() -1)
> db.source.find({"yourDateField":{$lt: date}}).forEach(
function(doc){
bulkInsert.insert(doc);
bulkRemove.find({_id:doc._id}).removeOne();
counter ++
if( counter % x == 0){
bulkInsert.execute()
bulkRemove.execute()
bulkInsert = db.target.initializeUnorderedBulkOp()
bulkRemove = db.source.initializeUnorderedBulkOp()
}
}
)
> bulkInsert.execute()
> bulkRemove.execute()