Lee Morgan
Lee Morgan

Reputation: 688

Find document with specific value from array within an array of subdocuments

I want to find all documents that have, in an array of subdocuments, a value that matches anything within another array.

Documents

{
    storeName: String,
    location: String,
    inventory: [{
        itemName: String,
        price: Number,
        otherDetail: String,
    }]
}

Example array

let itemNames = ["chair", "bed", "table"];

I am using aggregate. I need to find all stores (documents) that have in the inventory any of the itemNames in the array.

Upvotes: 0

Views: 38

Answers (1)

Kunal Mukherjee
Kunal Mukherjee

Reputation: 5853

Use a combination of $elemMatch operator along with $in to filter from your nested array.

var filter = {
    inventory: {
        $elemMatch: {
            itemName: {
                $in: ["chair", "bed", "table"]
            }
        }
    }
};

db.collection.find(filter);

With aggregate -

var pipeline = [
    {
        $match: {
            inventory: {
                $elemMatch: {
                    itemName: {
                        $in: ["chair", "bed", "table"]
                    }
                }
            }
        }
    }
];

db.collection.aggregate(pipeline);

Upvotes: 1

Related Questions