简体   繁体   中英

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM