Suppose I have a mongodb collections A and B.
While A has a foreign key to B called b_id.
How do I do in MongoDB (or even in ruby is better) the following query:
select * from A where b_id not in (select id from B where <some_condition> );
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
MongoDB doesn’t do relational queries (it’s not called NoSQL without cause) — but there are other ways you can accomplish this.
Run a two-step query in your Mongo client, first getting the inner array, then using the $nin operator:
var ids = db.B.find( conditions );
db.A.find( { b_id: { $nin: ids } } );
If you’re still in the design phase you can consider using nested documents for your schemas. For example, if B has many A, then you could add an array of A to each B as a property. (Keep in mind, though, that there is a limit to document size in MongoDB, so this is not a good solution if the number of A in any given B could be very large.)