tbowden
tbowden

Reputation: 1058

MongoDb match an unknown number of different values

I am trying to extract some data out of a MongoDB.

My DB looks something like this;

{
"name": "A",
"address": "London Road",
"values": [{"id": 1234, "name":"ABCD"},{"id": 6784, "name":"test"}]
}
{
"name": "B",
"address": "South Road",
"values": [{"id": 4327, "name":"guest"},{"id": 6743, "name":"demo"}]
}
{
"name": "C",
"address": "North Road",
"values": [{"id": 1234, "name":"ABCD"}]
}

I am trying to extract data based on the values id key.

So if I match 1234 to values id i'll return Elements A and C - I am able to do this.

The values I want to match may change, they could be 1234 or 6743 - returning Elements A, B and C.

I have created the below $or to handle this however the number of values to match varies, so the number of $or functions should change dependent on the number of values to match.

How do I create a query that allows me to match an unknown number of different values? - Maybe a loop?

Thanks in advance. I have search SO and the net and haven't had much success!

const orders = await findr.find({
    $or: [{
            values: {
                $elemMatch: {
                    id: "1234",

                }
            }
        },
        {
            values: {
                $elemMatch: {
                    id: "6743",

                }
            }
        }
    ]
}).toArray()

Upvotes: 0

Views: 29

Answers (1)

klhr
klhr

Reputation: 3390

You can write the query using $in: {"values.id": { $in: ["123", "456"] }}

$elemMatch isn't necessary because you're only specifying a single criterion.

Upvotes: 1

Related Questions