【问题标题】:How to merge two colletion in MongoDB of same type using single Query [duplicate]如何使用单个查询在相同类型的 MongoDB 中合并两个集合 [重复]
【发布时间】:2015-07-08 07:24:53
【问题描述】:

我有两个集合,分别是 AB,它们的文档如下:

集合A

{_id:id1
 name: Mohan
 age:25
}

集合 B

{_id:id2
 name: sohan
 age:29
}

我想合并这两个集合AB,预期输出如下:

{_id:id1,
 name: Mohan,
 age:25},
{_id:id2,
 name: Sohan
 age:29
}

有人知道如何合并这两个集合吗?而且我不想创建一个新集合。

【问题讨论】:

  • 你是在执行 JOIN 还是实际上是在合并两个集合?

标签: mongodb


【解决方案1】:

如果要将collection1的所有文档添加到collection2,那么你需要使用foreach函数,如下所示:

db.collection1.find().forEach(function(doc){db.collection2.save(doc)});

collection2 将包含 collection1 中的所有文档以及它自己的所有文档。

【讨论】:

  • 感谢您的快速回复。我想查询结果不保存在collection2中。还有其他选择吗?
猜你喜欢
  • 1970-01-01
  • 2020-03-24
  • 2016-09-27
  • 1970-01-01
  • 2020-09-19
  • 2012-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多