I am trying to do a very simple query joining two collections using aggregation.
I have two collections,
productSchema = new Schema({
product: { type: String },
price: { type: Number},
})
const inventoriesSchema= new Schema({
date: { type: Date},
products: [productSchema],
})
Now i want to bring all the products and inside of every product i want to bring the inventory.
This is what i am doing.
productModel.aggregate([
{
$lookup: {
from: 'inventories',
let: {
'product': { $toString: '$_id' }
},
pipeline: [
{
$match: {
'products._id': '$$product'
}
},
],
as: 'inventory',
}
},
])
i tried a lot of ways... with $toObjectId $toString... using $expr also like this...
{
$match: {
$expr: {
$and: [
{ $eq: ['$product._id', { $toString: "$$product" }] }
]
}
}
}
What i am doing wrong... ???
products&inventoriescollection which field has to be used to JOIN ? Doesproductfield is what we need to look ininventoriescollectionproductsarray ? Please provide sample docs & required o/p..