Sudharsan Venkatraj
Sudharsan Venkatraj

Reputation: 581

Mongoose query to list the document based on value from nested document

In this code i am trying to match the document based on product size from mongoose query. I tried this query but it doesn't works. Can anyone tell me what's wrong in this code?

Query i have passed:
{ $match: { "product_items.product_size": { value: 22, unit: "ml" } } }

** Structure:**

  [
    {
            "product_name": "sample product",
            "product_items": [
                {
                    "product_item_number": "796363011028",
                    "product_size": {
                        "value": 22,
                        "unit": "ml"
                    }
                }
            ]
        }
]

Upvotes: 1

Views: 108

Answers (1)

mickl
mickl

Reputation: 49985

It doesn't work this way because product_items.product_size evaluates to an array of objects and you are trying to compare a single object with such array. It is more reliable to use $elemMatch when working with arrays of objects:

db.collection.aggregate([
    {
        $match: {
            "product_items": {
                $elemMatch: {
                    "product_size.value": 22,
                    "product_size.unit": "ml"
                }
            }
        }
    }
])

Mongo Playground

Upvotes: 1

Related Questions