Sam Albert
Sam Albert

Reputation: 91

.find() in MongoDB with multiple conditions

I'm building a webapp using meteor and JavaScript, and want to filter a JSON object based on attribute. I can run fullList.find() to get everything and fullList.find({'Color': 'r'}) to get only "red" items, but I want to return all items that are either "red" or "blue", and can't figure out the proper syntax. I've tried various combinations such as fullList.find({'Color': 'r' || 'b'}) and fullList.find({'Color': ('r' || 'b')}), but it either doesn't run at all or returns items with only one attribute, rather than returning items with either. I feel like this should be an easy fix, I'm just not very familiar with JavaScript.

Here's my (relevant) code for completeness. Only the logic for two conditions being true (as opposed to one or three) is failing:

indicadores: function(){
        if (Session.get("displayUrgencies")){
            if (Session.get("displayInsuff")){
                if (Session.get("displayStrengths")){
                    console.log("display all");
                    return fullList.find();
                }
                else {
                    console.log("display urgencies and insufficiencies");
                    return fullList.find({'Color': 'v' || 'r'});
                }
            }
            else {
                if (Session.get("displayStrengths")){
                    console.log("display urgencies and strengths");
                    return fullList.find({'Color': 'b' || 'r'});
                }
                else {
                    console.log("display urgencies");
                    return fullList.find({'Color': 'r'});
                }
            }
        }
        else if (Session.get("displayInsuff")){
            if (Session.get("displayStrengths")){
                console.log("display insufficiencies and strengths");
                return fullList.find({'Color': 'v' || 'b'});
            }
            else {
                console.log("display insufficiencies");
                return fullList.find({'Color': 'v'});
            }
        }
        else if (Session.get("displayStrengths")){
            console.log("display strengths");
            return fullList.find({'Color': 'b'});
        }
        else {
            console.log("display all (default)");
            return fullList.find();
        }       
    },

Upvotes: 3

Views: 13346

Answers (1)

halbgut
halbgut

Reputation: 2386

This .find function isn't a part of JS itself. It's a property of a MongoDB collection. You can simply use the $or MongoDB selector. Like this:

fullList.find({
  $or: [
    {'Color': 'r'},
    {'Color': 'b'}
  ]
})

In your example fullList is the MongoDB collection. You can read more about them here.

Upvotes: 9

Related Questions