Example join collection in mongodb with nodejs use mongoose

Join Collections

MongoDB is not a relational database, but you can perform a left outer join by using the $lookup stage.

The $lookup stage lets you specify which collection you want to join with the current collection, and which fields that should match.

Consider you have a "orders" collection and a "products" collection:

 

orders:

 

[

  { _id: 1, product_id: 154, status: 1 }

]

 

products:

 

[

  { _id: 154, name: 'Chocolate Heaven' },

  { _id: 155, name: 'Tasty Lemons' },

  { _id: 156, name: 'Vanilla Dreams' }

]

 

Example: Join the matching "products" document(s) to the "orders" collection

 

var mongoose = require('mongoose');

var db = mongoose.connection;

var Schema = mongoose.Schema;

db.on('error', console.error);

db.once('open', function () {

    console.log("db connect");

     db.collection('orders').aggregate([

        {$lookup:

                    {

                        from: 'products',

                        localField: 'product_id',

                        foreignField: '_id',

                        as: 'orderdetails'

                    }

        }

    ]).toArray(function (err, res) {

        if (err)

            throw err;

        console.log(JSON.stringify(res));

        db.close();

    });

});

mongoose.connect('mongodb://192.168.1.122:27017/codewr'); 

  

 

Run and result:

 

C:\Nodejs>node mongooseJoin2Collection.js

db connect

[{"_id":1,"product_id":154,"status":1,"__v":0,"orderdetails":[{"_id":154,"name":"Chocolate Heaven","__v":0}]}]

 

As you can see from the result above, the matching document from the products collection is included in the orders collection as an array.