mongodb 将文档从一个集合移动到另一个集合 [英] mongodb move documents from one collection to another collection

查看:67
本文介绍了mongodb 将文档从一个集合移动到另一个集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 MongoDB 中将文档从一个集合移动到另一个集合??例如:我在集合 A 中有很多文档,我想将所有 1 个月前的文档移动到集合 B(这些 1 个月前的文档不应该在集合 A 中).

How can documents be moved from one collection to another collection in MongoDB?? For example: I have lot of documents in collection A and I want to move all 1 month older documents to collection B (these 1 month older documents should not be in collection A).

使用聚合,我们可以复制.但我想做的是移动文档.有什么方法可以移动文档?

Using aggregation we can do copy. But what I am trying to do is moving of documents. What method can be used to move documents?

推荐答案

更新 2

请不要再给这个答案点赞了.正如所写,@jasongarber 的回答在任何方面都更好.

Please do NOT upvote this answer any more. As written @jasongarber's answer is better in any aspect.

更新

@jasongarber 的这个答案 是一种更安全的方法,应该使用而不是我的方法.

This answer by @jasongarber is a safer approach and should be used instead of mine.

如果我说对了,并且您想移动 1 个月以上的所有文档,并且您使用的是 mongoDB 2.6,则没有理由不使用批量操作,这是我所知道的执行多项操作的最有效方法:

Provided I got you right and you want to move all documents older than 1 month, and you use mongoDB 2.6, there is no reason not to use bulk operations, which are the most efficient way of doing multiple operations I am aware of:

> 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()

这应该非常快,而且它的优点是,如果在批量插入过程中出现问题,原始数据仍然存在.

This should be pretty fast and it has the advantage that in case something goes wrong during the bulk insert, the original data still exists.

编辑

为了防止占用过多内存,您可以对每个处理的x文档执行批量操作:

In order to prevent too much memory to be utilized, you can execute the bulk operation on every x docs processed:

> 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()

这篇关于mongodb 将文档从一个集合移动到另一个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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