Jon
Jon

Reputation: 277

MongoDB: How to find a document sharing a list element with specified list

I'm currently using mongoose schemas where some of the values hold lists. For example:

var dinerSchema = mongoose.Schema({
  restaurants: [String]
});

I'm looking for a way to write a mongo query that finds other documents which have at least one shared element between the two values. For example if I'm given a list of restaurants which is

[McDonalds, Burger King, Wendy's]

I want to find other documents which have restaurant values such as

[Sonic, Taco Bell, Burger King]

but not

 [Red Lobster, Olive Garden, Legal Sea Foods]

I'm aware if I wanted to find documents given a single value I could do something like

dinerModel.find({ restaurants: "McDonalds" }, ...);

To return all documents which contain McDonalds in their restaurant list. However, I want to find any documents which contain ANY of the elements in a certain list. Is there a way to query for this? I don't think I can just do "or" queries because I don't know the size of the list of restaurants that I'll be looking for, and it could change from query to query.

Thanks!

Upvotes: 1

Views: 32

Answers (1)

Scott Stensland
Scott Stensland

Reputation: 28305

Do a find with $in clause :

dinerModel.find({
    'restaurants': { $in: [
        'Sonic',
        'Taco Bell', 
        'Burger King'
    ]}
}, function(err, docs){
    if (err) {
        console.log(err); // deal somehow
        return;
    }
    console.log(docs);
    }
});

Upvotes: 2

Related Questions