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

Mongodb相关问答推荐

使用查询参数过滤MongoDB Go驱动程序时出现问题

映射数组值并查找每个匹配的集合

MongoDB(Mongoose)条件判断没有像我预期的那样工作

在对象mongodb的数组中查找元素

MongoDB 根据最新日期查询多个不同的值

定期自动轮换 MongoDb 集合

管道聚合mongodb同一$project阶段的计算字段?

DB 中的引用对象在 GraphQL 查询中返回 null

Mongoose 更新不同类型的记录

在我的查询中使用 populate() 时的 MongoDB createIndex()

从 mongodb Golang 检索时判断零等效时间.时间

如何在mongoDB中按嵌套文档分组( group by )

无法提取地理键,经度/纬度超出范围

mongoose如何在幕后工作

Java MongoDB/BSON 类混淆

如何在 MongoDB 中进行内部连接?

如何返回 MongoDB 中文档的 ObjectId 或 _id?和错误$in 需要一个数组

有没有办法自动更新 MongoDB 中的两个集合?

MongoException: Index with name: code already exists with different options

多次使用位置 `$` 运算符来更新嵌套数组