Reputation: 688
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
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