Combine 2 collections into a single collection mongoDB

I have 2 collections in mongoDB

collection 1

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

collection 2

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

I'm trying to combine write a query that gives me an output like so

Output

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

I've tried lookup but that seems to append 1 collection to the other, I want the collections to be merged like shown in the output. I have looked at the existing solutions on stack overflow and they all suggest using lookup which does not give me the output that I require.

2 answers

  • answered 2019-04-15 06:13 Jack Bashford

    Make two independent queries and combine them:

    const output = [query1, query2];
    

  • answered 2019-04-15 12:39 krishna Prasad

    This can be done through javascript code on mongo shell as follow:

    > 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"
        }
    ]
    

    Hope this will help you. You can perform this on mongo shell.