2

I have some problems with mongoDB, i looked for an answer but i couldn't find anything that solves my problem....

db.coders.save( {
'name': 'John', 
'languages' : { 'php':'bad','java':'good','brainfuck':'very bad'} 
});

db.coders.save( {
'name': 'Sarah', 
'languages' : { 'php':'good','java':'bad','brainfuck':'very bad'} 
});

db.coders.save( {
'name': 'Tom', 
'languages' : { 'php':'very good','java':'good','brainfuck':'bad'} 
});

now i want to find any coder that knows any language 'very good'...how?

2 Answers 2

5

You could not find it because it is impossible. None of the search operators works on the schema you provided.

The easiest workaround is to change schema a little bit:

db.coders.save( {
'name': 'John', 
'languages' : [ { n: 'php', v: 'bad'},{n:'java', v: 'good'},{n : 'brainfuck', v: 'very bad'}] 
});

In such a case you can query the data using the following query:

db.coders.find({'languages.v' : 'good'})
Sign up to request clarification or add additional context in comments.

Comments

2

I agree with Salvador, that changing the schema is better.

But I found that you can search using the $where operator.

db.coders.find({ $where : function() { for(lang in this.languages) { if (this.languages[lang] == 'very good') { return true; }  } return false;  }});

It might be a bit slowly as pointed in the docs.

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-JavascriptExpressionsand%7B%7B%24where%7D%7D

Comments

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.