0

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... ???

1
  • What is the relation between products & inventories collection which field has to be used to JOIN ? Does product field is what we need to look in inventories collection products array ? Please provide sample docs & required o/p.. Commented Apr 30, 2020 at 16:31

1 Answer 1

1

Try below aggregation query which uses $in to check whether an expression exists in array or not :

Assuming your product field in products Coll is key to join & needs to be checked in products array of inventories Coll.

productModel.aggregate([
    {
        $lookup: {
            from: 'inventories',
            let: { 'product': '$product' }, // create local variable for products
            pipeline: [
                { $match: { $expr: { $in: [ "$$product",  "$products" ] } } } // check product from products Coll exists in products of inventories Coll
            ],
            as: 'inventory'
        }
    }
  ])
Sign up to request clarification or add additional context in comments.

1 Comment

uhh.... i was missing $in to check the _id inside the array... i was just trying to $match the inventories that contains the product inside... thanks for your quick answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.