繁体   English   中英

将2个集合合并到一个集合mongoDB中

[英]Combine 2 collections into a single collection mongoDB

我在mongoDB中有2个集合

收集1

  {
    _id : "123",
    name : "ABC1"
  }

收集2

  {
    _id : "456",
    name : "DEF1"
  }

我正在尝试结合写一个查询,给我一个像这样的输出

产量

  [
    {
      _id : "123",
      name : "ABC1"
    },
    {
     _id : "456",
     name : "DEF1"
    }
  ]

我尝试过查找,但似乎将1个集合附加到另一个集合,我希望合并集合,如输出中所示。 我已经查看了堆栈溢出的现有解决方案,他们都建议使用lookup ,这不会给我我需要的输出。

进行两个独立的查询并将它们组合在

const output = [query1, query2];

这可以通过mongo shell上的javascript代码完成,如下所示:

> var all = []; // initialize a variable with empty values

> db.collection1.find().forEach(function (obj) {all.push(obj);}) // push to all from collection 1

> db.collection2.find().forEach(function (obj) {all.push(obj);}) // push to all from collection 2

> printjson(all) // Print all pushed elements 
[
    {
        "_id" : "123",
        "name" : "ABC1"
    },
    {
        "_id" : "456",
        "name" : "DEF1"
    }
]

希望这会帮助你。 你可以在mongo shell上执行此操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM