Match based on a field only with non-empty array

Tags: , , ,



I am trying to do a filter on something. Here is a simplified layout of my Order model:

{
    merchant: <Reference to the merchant>,
    date: <Date Object>
    name: "Some order name",
    ingredients: [{
        ingredient: {data: "some data"}
        otherData: "some data"
    }]
}

I want to query the documents based on the ingredients that they contain. I have an array of items to search through “objectifiedIngredients”. If it has ingredients in it, then I want to search for orders that contain that ingredient. If the array is empty, then I want to not do the query and just get all orders. “objectifiedIngredients” is a list of ObjectId’s. Here is what I have so far:

      Order.aggregate([
            {$match:{
                merchant: new ObjectId(req.session.user),
                date: {
                    $gte: from,
                    $lt: to
                },
                ingredients: {
                    $elemMatch: {
                        ingredient: {
                            $in: objectifiedIngredients
                        }
                    }
                }
            }}
        ])

How can I run the $match on ingredients only if the array has elements in it? I have tried using $cond, but either it doesn’t work here or I didn’t use it right.

Answer

Try this

Order.aggregate([
            {$match:{
                merchant: new ObjectId(req.session.user),
                date: {
                    $gte: from,
                    $lt: to
                },
                ingredients: {
                    $ne: false
                }
            }}
        ])

You can check for more details here



Source: stackoverflow