Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get data referencing form one collection to another? Mongodb

router.get('/productSelect', (req, res, next) =>{
    productSchema.aggregate([   
        { $lookup:
            {
                from: 'supplierSchema',
                localField: 'supplierId',
                foreignField: '_id',
                as: 'supplier'
            }
        }

    ], (err, productSchema) =>{
        if(err) res.json(err);
        else res.json(productSchema);
    });
});

I want to get data from collection

[
  {
    "_id": "5ba26ff33318b51e20a80fb3",
    "productExist": true,
    "productName": "Anything",
    "supplierId": "5b9d25064dcf2327b449ae1b",
    "brandId": "5b9d162a316e8d2660f26393",
    "categoryId": "5ba2509a6367372568b1ce6d",
    "productPrice": 222,
    "productQuantity": 320,
    "productMax": 3,
    "productMin": 4,
    "productTimeStamp": "2018-09-19T15:49:07.177Z",
    "__v": 0
  }
]

and replace the supplierId as supplierName from collection

[
  {
    "_id": "5b9d25064dcf2327b449ae1b",
    "supplierExist": true,
    "supplierName": "NBA World Wide",
    "supplierStatus": "Available",
    "supplierTimeStamp": "2018-09-15T15:28:06.971Z",
    "__v": 0
  }
]
like image 617
C.E James Avatar asked Dec 05 '25 07:12

C.E James


1 Answers

For making join with two table you have make sure that the type for both the fields i.e. localField and foriegnField should be the same.

Or

With mongodb 4.0 you can easily change the type of the String to ObjectId using $toObjectId aggregation

productSchema.aggregate([   
  { "$lookup": {
    "from": "supplierSchema",
    "let": { "supplierId": { "$toObjectId": "$supplierId" }},
    "pipeline": [
      { "$match": { "$expr": { "$eq": ["$_id", "$$supplierId"] }}}
    ]
    as: "supplier"
  }}
])
like image 176
Ashh Avatar answered Dec 07 '25 23:12

Ashh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!