MongoDB Mongoose Use Lookup Guide
In This Blog We Will See Complete Guide For Using Joins With Lookup in Mongoose
Simply in MongoDB Mongoose we can use Aggregate Query with $lookup to get data basis upon JOINS. such as below:
await MainModel.aggregate([
{
$match:
{ "COLUMN_NAME": value }
},
{
$lookup:
{
from: 'relation_collection_name',
localField: 'relation_collection_primary_key',
foreignField: 'this_table_foreign_key',
as: 'ALIASING'
}
}
]);
With above query new column added with ALIASING in which relation collection data will also come.
To get data in Object format instead of Array we can use $unwind like below:
await MainModel.aggregate([
{
$match:
{ "COLUMN_NAME": value }
},
{
$lookup:
{
from: 'relation_collection_name',
localField: 'relation_collection_primary_key',
foreignField: 'this_table_foreign_key',
as: 'ALIASING'
}
},
{
$unwind: '$ALIASING'
},
]);
With. above query via using $unwind the data coming in object format now instead of array.
Now, if you want data if no data available in relation table so we can use preserveNullAndEmptyArrays like below:
await MainModel.aggregate([
{
$match:
{ "COLUMN_NAME": value }
},
{
$lookup:
{
from: 'relation_collection_name',
localField: 'relation_collection_primary_key',
foreignField: 'this_table_foreign_key',
as: 'ALIASING'
}
},
{
$unwind: {
path: "$ALIASING",
preserveNullAndEmptyArrays: true
}
},
]);
Now, if you want to use multiple lookup so you can use very simple like below:
await MainModel.aggregate([
{
$match:
{ "COLUMN_NAME": value }
},
{
$lookup:
{
from: 'relation_collection_name',
localField: 'relation_collection_primary_key',
foreignField: 'this_table_foreign_key',
as: 'ALIASING'
}
},
{
$unwind: {
path: "$ALIASING",
preserveNullAndEmptyArrays: true
}
},
{
$lookup:
{
from: 'relation_collection_name_another',
localField: 'relation_collection_primary_key',
foreignField: 'this_table_foreign_key',
as: 'ALIASING_1'
}
},
{
$unwind: {
path: "$ALIASING_1",
preserveNullAndEmptyArrays: true
}
},
]);
Thanks for reading this blog, I hope it will help you to understand Mongoose $Lookup.
Happy Coding !!
Follow Me Here.
Comments
Post a Comment