如何将许多文档合并为一个文档并移至另一个集合? [英] How can I merge many documents into a single document and move to another collection?

查看:61
本文介绍了如何将许多文档合并为一个文档并移至另一个集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况:

  • 一个收藏集中有50个文档
  • 想将其移入1个文档
day: {data:data,data:data}
day: {data:data,data:data}

此数据应变为:

week:[day,day,day..]

这是一次工作.我想在命令行或Robomongo中做到这一点.

This is a one time job. I want to do it in the command line or Robomongo.

推荐答案

由于我们看不到您的确切文档结构,因此,我将尝试给出一个简单的解决方案,无论您的文档具有什么结构,该解决方案都应该起作用.

Since we can't see your exact document structure, I'll try to give a simple solution that should work no matter what structure your documents have.

基本上,您需要遍历源集合中的每个文档,并生成一个包含所有值的数组.

Basically you would want to iterate over each of the documents in the source collection and generate an array of all the values.

week_array = []
db.source_col.find({}).forEach( function( doc ){
  week_array.push( doc );
} );

您现在有了一个数组,其中包含source_collection中的所有文档.现在,您要做的就是构造一个新文档,并将数组插入到正确属性处:

You now have an array containing all the documents from the source_collection. All you have to do now is construct a new document and insert the array into it at the correct attribute:

var week_doc = { "week": week_array };

现在只需将其插入目标集合中即可

Now just insert it into the target collection:

db.target_col.insert( week_doc );

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

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