Reputation: 3280
Say if there're two simple Mongo documents, Person and Class. Person references Class to model a many-to-many this-person-takes-these-classes relationship. How do I find the person that is not registered in ANY classes (that has no references to any Class)?
I tried the following but didn't seem to work:
db.people.find({"class": {$exists: false}});
The above returns all the people, even the ones that are taking classes.
Appreciate any input. Thanks!
Upvotes: 2
Views: 1040
Reputation: 45287
Person references Class to model a many-to-many this-person-takes-these-classes relationship.
First you have to define how this is modeled. There are three ways to do this with MongoDB.
Based on your query, it looks like you have #3, but that is not a given.
How do I find the person that is not registered in ANY classes?
This will be very specific to how your data is actually stored in the DB.
Let's say that people
contains an array of references to classes
, your data will probably look like this:
{ _id: "John", classes: [ 'math', 'science', 'english' ] }
{ _id: "Mary", classes: [ 'computers', 'biology' ] }
{ _id: "Steve", classes: [ ] }
In this case "Steve" clearly has no classes. Your query is looking for people
where classes
does not exist. But in this case, classes
does exist, it's just empty.
If your data looks like this, you probably want to use the [$size][1]
operator.
Upvotes: 4