0

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.

2
  • FYI, if you answered/saw my other question, sorry, I got my data structure wrong and thought it would be better to just ask another question. Commented Jul 18, 2020 at 8:43
  • 1
    What you have tried? what you are getting after try? Commented Jul 18, 2020 at 8:52

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

The problem with this though, is that I am using aggregation and I cannot use $elemMatch with aggregation.
@LeeMorgan updated my answer for usage with Aggregate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.