user2567834
user2567834

Reputation: 41

MongoDB: How to find key by value

I'm using Node.js with express framework and Mongoose (MongoDB), and I have a question about how to effectively retrieve data.

Let's say I have something like this on a mongo document:

test : {a:1, b:2, c:2, d:1};

It's easy to retrieve the value of keys (a,b,c, or d), but how to do the inverse, for example retrieve all the letters that have value 2 (in my example it would be 'b' and 'c')

Thanks!

Upvotes: 1

Views: 942

Answers (1)

alfonsodev
alfonsodev

Reputation: 2754

var test = {a:1, b:2, c:2, d:1};

var search = function(obj, value) {
    for(var key in obj) {
        if(test[key] === value) {
            console.log(key);
        }
    }
};

search(test, 2);

//output b c 

Be careful if you have modified Object.prototype then you could have unwanted prototype keys, and you should control it.

Upvotes: 2

Related Questions