Mongodb combining queries -
i have 2 collections:
collection 1: tags
{ "tagname":"tag1", "tagid":"id1" }
collection 2: questions
{ "questionid":"1". "title":"question title", "tags":tag1 }
i want know query can give me tags no questions.
in sql select * tags tagname not in (select tags questions)
form shell can
var c = db.questions.distinct('tags');
db.tags.find({tagname:{$nin:c}})
how do same in java
you can't in 1 step current schema. in order this, need store question ids each tag instead of have now. generally, in mongodb store relations between collections "the other way around" compared relational database. example, can store as:
tags
{ "tagname": "tag1", "tagid": "id1", "questions" : [ 1, 3 ] } { "tagname": "tag2", "tagid": "id2" }
questions
{ "questionid": 1. "title": "question title" } { "questionid": 2, "title": "question title" } { "questionid": 3, "title": "question title" }
or perhaps also tags:
{ "questionid": 1. "title": "question title", tags: [ "id1" ] } { "questionid": 2, "title": "question title" } { "questionid": 3, "title": "question title", tags: [ "id1" ] }
which variant pick depends bit on data needs. store tags questions, and questions tags uses more storage , causes more work if need update tags/question, make queries easier. example, can ask tags without questions after above modifications with:
db.tags.find( { questions: { $exists: true } } );
to query in java, suggest have @ http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/ has lots of examples. bit further down is: http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/#getting-a-set-of-documents-with-a-query indicates above query like:
query = new basicdbobject("questions", new basicdbobject("$exists", true));
Comments
Post a Comment